开发者

Accessing the variable created by using attr_accessor

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

def color
  @color
end

def color=(value)
  @color = value
end

The thing I don't understand is why in the following code, why can't I use color= in my initializer? (it ends up being blank). Why do I need to use @color= or self.color= instead? Shouldn't color= be a way to 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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜