Ruby 从类内部使用attr_访问器?
我试图从定义它的类内部使用Ruby 从类内部使用attr_访问器?,ruby,attr-accessor,Ruby,Attr Accessor,我试图从定义它的类内部使用attr\u访问器,但没有用。为什么这不起作用 我希望IRB中的“新”输出如下: 我可以看到thing=方法已经定义。我不明白为什么在我尝试更改值时没有调用该方法。试试这个- class StringClass ...... def change self.thing = "new" end end foo=StringClass.new foo.change=>“新建” 也就是说,因为应该使用self调用这些方法: class Str
attr\u访问器
,但没有用。为什么这不起作用
我希望IRB中的“新”输出如下:
我可以看到thing=
方法已经定义。我不明白为什么在我尝试更改值时没有调用该方法。试试这个-
class StringClass
......
def change
self.thing = "new"
end
end
也就是说,因为应该使用
self
调用这些方法:
class StringClass
def initialize
@thing = "old"
end
attr_accessor :thing
def output
puts self.thing
end
def change
self.thing = "new"
end
end
谢谢我真的不明白为什么,当一个人不必为“正常”定义的方法这么做时。@Deejay-with syntaxt“而不是”
self
,Ruby不知道你是在尝试调用一个方法(你知道它,因为你了解上下文),还是只想创建一个局部变量。如果您不指定self
,在这种情况下它将创建一个局部变量。谢谢,您是对的,这是一个重复。如何最好地解析?因为您只是从类中引用实例变量,所以最好不用attr_访问器,只使用@符号。
class StringClass
......
def change
self.thing = "new"
end
end
class StringClass
def initialize
@thing = "old"
end
attr_accessor :thing
def output
puts self.thing
end
def change
self.thing = "new"
end
end