从下面的代码中可以看出,|| =运算符正在从类外部进行求值.
class Foo attr_reader :bar def baz self.bar ||= 'baz' end private attr_writer :bar end puts Foo.new.baz # => in `baz': private method `bar=' called for #<Foo:0x007fd9720829a8> (NoMethodError)
从Ruby: Official expansion of ||= conditional assignment operator接受的答复中引用:
In other words,the expansion c = c || 3 is (excluding bugs like in pre-1.9) correct.
将baz方法重写为self.bar = self.bar || ‘baz’不会引起错误.
我正在寻找一个关于Ruby如何以及为什么以这种方式行事的明确答案,因为它似乎是反直觉的.
这个行为存在于Ruby版本1.9.3,2.0.0和2.1.2上,这导致我相信这不是一个错误.
解决方法
看起来像一个
bug.
更新:bug在中继线是fixed,是slated for back porting to 2.1 and 2.0.
请注意,问题比这更普遍,对于所有缩写的分配,它不再是有条件的缩写分配:
private def foo=(*) end public def foo; 0 end self.foo = 42 self.foo += 42 # private method `foo=' called for main:Object (NoMethodError) private :foo self.foo += 42 # private method `foo' called for main:Object (NoMethodError)