【发布时间】:2015-08-30 21:45:49
【问题描述】:
我试图在定义它的类中使用attr_accessor,但无济于事。为什么这不起作用?
我希望以下内容在 IRB 中输出“新”:
irb(main):016:0> foo = StringClass.new
=> #<StringClass:0x2fbf2c0 @thing="old">
irb(main):017:0> foo.output
old
=> nil
irb(main):018:0> foo.change
=> "new"
irb(main):021:0> foo.output
old
=> nil
这是实现:
class StringClass
def initialize
@thing = "old"
end
attr_accessor :thing
def output
puts thing
end
def change
thing = "new"
end
end
我可以看到 thing= 方法已定义。我不明白为什么当我尝试更改值时没有调用该方法。
【问题讨论】:
-
谢谢,你说得对,这是重复的。如何最好地解决?
-
由于您只是在类中引用实例变量,也许最好不要使用 attr_accessor,而只需使用 @ 符号。
标签: ruby attr-accessor