In the last post we saw that, what attribute accessors methods are and how it can be used. In this post, we’ll see how actually these accessors are implemented.
lets take the example from last post and see why errors were thrown in some cases :-
class Person attr_accessor :age attr_writer :name attr_reader :gender end 1.9.3-p125 :013 > p = Person.new => #<Person:0x00000001309c00> 1.9.3-p125 :014 > p.age=20 => 20 1.9.3-p125 :015 > p.age => 20 1.9.3-p125 :016 > p.name='vikram' => "vikram" 1.9.3-p125 :017 > p.name NoMethodError: undefined method `name' for #<Person:0x00000001309c00 @age=20, @name="vikram"> from (irb):17 from /home/inbelu013521a/.rvm/rubies/ruby-1.9.3-p125/bin/irb:12:in `' 1.9.3-p125 :018 > p.gender => nil 1.9.3-p125 :019 > p.gender='male' NoMethodError: undefined method `gender=' for #<Person:0x00000001309c00 @age=20, @name="vikram" > from (irb):19 from /home/inbelu013521a/.rvm/rubies/ruby-1.9.3-p125/bin/irb:12:in `'
Lets analyze all three accessor methods one by one and see what is happening behind the scene.
In above example we saw that, we can read and write the attribute age, only write the attribute name and only read the attribute gender and that happens because behind the scene ruby translates the method call
attr_accessor :age
into
def age=(value) @age = value end def age @age end
attr_writer :name
into
def name=(value) @name = value end
attr_reader :gender
into
def gender @gender end
So, now it makes clear that why those method calls were throwing error.