Skip to content

Instantly share code, notes, and snippets.

@mayfer
Created July 24, 2015 18:47
Show Gist options
  • Save mayfer/6ba99fe2cb16eca3c515 to your computer and use it in GitHub Desktop.
Save mayfer/6ba99fe2cb16eca3c515 to your computer and use it in GitHub Desktop.
Ruby Review & Object Oriented Programming
people[0][:emails][2][:a]
((5 + 3) * 8 / 9 - 2)
subtract(divide(multiply(add(5, 3), 8), 9), 2)
people = [
{
name: "murat",
phone: "345345",
handles: {
twitter: "@poophead",
}
emails: ["[email protected]", "[email protected]", {a: 5}],
},
{
name: "murat",
phone: "345345",
},
{
name: "murat",
phone: "345345",
},
]
people.each do |person|
person.each do |key, value|
puts "#{key}: #{value}"
end
if person.has_key?(:handles)
person[:handles].each do |type, handle|
puts " #{type}: #{handle}"
end
end
end
people_with_phones = people.select do |person|
person.has_key?(:phone)
end
people_with_phones = []
people.each do |person|
if person.has_key?(:phone)
people_with_phones << person
end
end
phones = people.map do |person|
person[:phone]
end
# ["2343245", "456456"]
# class, is the blueprint
# class can have methods and variables. class methods, class variables
# an instance is created from a class. a.k.a. an object.
# instances have instance variables and instance methods
# classes can inherit from previously defined classes
# they can override methods. they can reuse inherited methods (super)
# methods can be public or private (called from outside vs. only inside the class)
# getter and setters can conveniently be defined via "attr_accessor :attribute_name"
class Person
attr_accessor :name
@@population = 0
def initialize(name)
@name = name
capitalize
if @name != "lil jonny"
@@population += 1
end
end
def name=(name)
@name = name
capitalize
end
# INSTANCE method
def capitalize
capitalized_names = @name.split(" ").map do |subname|
subname.capitalize
end
new_name = capitalized_names.join(" ")
@name = new_name
return new_name
end
# CLASS method
def self.population
@@population
end
end
class Student < Person
attr_accessor :student_id, :gender
@@student_population = 0
def initialize(name, gender)
@@student_population += 1
@gender = gender
# also increase general population
super(name)
end
end
puts "population: #{Person.population}"
# person1 is an OBJECT, a.k.a an INSTANCE, of the CLASS Person
person1 = Person.new("murat ayfer")
person1.name = "ayfer murat"
puts person1.name
person2 = Person.new("khurram")
# puts person2.capitalize
student1 = Student.new("i don't know your names yet", "male")
student1.student_id = 384583745
puts student1.inspect
puts "population: #{Person.population}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment