attr_accessor is used to create setter and getter methods for instance variables so that they can be accessed outside the class. initialize is the special method in ruby that gets called when an object is instantiated.
class Birthday
attr_accessor :name
def initialize age, gender
@age = age
self.gender = gender
end
end
bday = Birthday.new "30", "Male"
puts bday.name # nil as initializer dont have name. yields results if set in before step like bday.name = "Bob"
puts bday.age # undefined method `age` as no attr_reader defined for age
puts bday.gender # undefined method `gender=' as no attr_writer defined for gender
# to fix the issues
class Birthday
attr_accessor :name, :gender, :age
def initialize age, gender, name
@age = age
self.gender = gender ## call attr_writer of @gender
@name = name
end
end
Posted by Sandheep to Sandheep's deck (2013-05-22 18:33)