Access to a variable created with attr_accessor

I'm trying to figure out what attr_accessor gives me access attr_accessor . From what I understand, it provides getter and setter methods. So attr_accessor :color it will create for me something like the following

 def color @color end def color=(value) @color = value end 

I do not understand why in the following code why I can not use color= in my initializer? (it ends up empty). Why do I need to use @color= or self.color= instead? Shouldn't color= call the setter method that was just created for me above?

 class Bird attr_accessor :color def initialize(c="green") color = c # this doesn't work # either one of the following DOES work # @color = c # self.color = c end end puts Bird.new.color # prints nothing unless using @color or self.color 
+4
source share
1 answer

An expression like color = "green" assigns "green" local variable, not an attribute. Attribute adjusters always need a receiver, even if the receiver is self .

+5
source

All Articles