An example will explain the question:
Val = Struct.new(:value) do
def inc
p value
value = value + 1
end
end
v = Val.new(1)
v.inc
The output will be:
1
undefined method `+' for nil:NilClass (NoMethodError)
Why do I get this error when value is clearly not nil? Is there a way to make this work?
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
Clarification on Sergio's answer.
Within inc's definition, there is initially no variable value, and what is called by p value is the method value, which returns 1.
Then in line value = value + 1, at the point when value = has been parsed, a local variable value is created and is initialized to nil. Even though value + 1 is evaluated prior to assignment of its value into the newly created value, the initialization of value takes place first. So, when value + 1 is to be evaluated, there already is a local variable value, which has priority to be called over the method value. And this value is nil.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With