以下代码导致了我的问题:
class Foo
def initialize(n=0)
@n = n
end
attr_accessor :n
def inc
n+=1
end
end
打电话Foo.new.inc
提高了NoMethodError: undefined method '+' for nil:NilClass
电话Foo.new.n
收益0
为什么会Foo.new.inc
引发错误?我可以做到Foo.new.n+=1
。
tldr; self.n = x
必须始终使用某种形式的来分配给设置员。
考虑到n += x
膨胀到n = n + x
其中n为绑定为一个局部变量,因为它出现在赋值的左侧。局部变量的这种“引入”抵消了对自身隐式方法调用(例如n
-> self.n
)的正常回退行为。
因此,由于n
尚未分配(但现在已绑定为局部变量),因此表达式的计算 n = nil + x
结果是导致异常引发的原因。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句