一个例子将解释这个问题:
Val = Struct.new(:value) do def inc p value value = value + 1 end end v = Val.new(1) v.inc
输出将是:
1 undefined method `+' for nil:NilClass (NoMethodError)
为什么在value
明显不为零时会出现此错误?有没有办法让这项工作?
Val = Struct.new(:value) do def inc p value # here it still prints 1 # but here you REDEFINED what value is. It is now a local variable! # Also its initial value is nil, hence the error you're getting. value = value + 1 # should have used this instead, to reference the method self.value = value + 1 end end