Ruby on rails 访问使用attr_访问器创建的变量
我正在试图理解Ruby on rails 访问使用attr_访问器创建的变量,ruby-on-rails,ruby,Ruby On Rails,Ruby,我正在试图理解attr\u accessor为我提供了什么访问权限。据我所知,它提供了getter和setter方法。因此attr\u accessor:color它将为我创建如下内容 def color @color end def color=(value) @color = value end 我不明白的是,为什么在下面的代码中,我不能在我的初始值设定项中使用color=?(结果是空的)。为什么我需要使用@color=或self.color=?color=不应该是调用刚才为我创
attr\u accessor
为我提供了什么访问权限。据我所知,它提供了getter和setter方法。因此attr\u accessor:color
它将为我创建如下内容
def color
@color
end
def color=(value)
@color = value
end
我不明白的是,为什么在下面的代码中,我不能在我的初始值设定项中使用color=
?(结果是空的)。为什么我需要使用@color=
或self.color=
?color=
不应该是调用刚才为我创建的setter方法的一种方式吗
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
类似于
color=“green”
的表达式将“green”
赋值给局部变量,而不是属性。属性设置者总是需要一个接收者,即使接收者是self
一个相关的问题,是self.color
要走的路还是@color
?@Dty,一个非常好的问题。我想说的是,在类实现本身中,使用@color
是可以的。但是,在包含的模块和任何子类中,我建议不要直接使用@color
(而是使用color
或self.color
,以及self.color=
)。在派生类或包含的模块中使用实例变量违反了封装,尽管Ruby很乐意让您这样做。我最近发现,如果您想要运行setter方法,您应该使用self.color
。使用@self.color
将绕过setter方法。