我想为一个对象定义一个新的 getter 方法。这是我在 irb
中编写的代码:
> eigenclass = class << self; self; end
> eigenclass.class_eval { attr_reader :foo }
我想这段代码应该向 self 对象添加 foo
方法。但下一行说不同
puts foo
=> nil
foo = 1
=> 1 #Why is there no exception?
puts foo
=> 1
puts @foo
=> nil
这是为什么?
最佳答案
那是因为 var = val
分配一个局部变量而不是调用 setter
方法。
你需要在它前面加上 self.
以便调用 setter(如果你有一个同名的局部变量,则调用实际的 getter),这会抛出你期望的错误:
2.0.0p195 :001 > eigenclass = class << self; self; end
=> #<Class:#<Object:0x007fc6f98e24d0>>
2.0.0p195 :002 > eigenclass.class_eval { attr_reader :foo }
=> nil
2.0.0p195 :003 > foo
=> nil
2.0.0p195 :004 > foo = 20
=> 20
2.0.0p195 :005 > foo
=> 20
2.0.0p195 :006 > self.foo
=> nil
2.0.0p195 :007 > self.foo = 20
NoMethodError: undefined method `foo=' for main:Object
from (irb):7
关于ruby - 无法在 Ruby 的特征类中定义 getter 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17379364/