The following code is causing me issues:
class Foo
def initialize(n=0)
@n = n
end
attr_accessor :n
def inc
n+=1
end
end
Calling Foo.new.inc
raises NoMethodError: undefined method '+' for nil:NilClass
Calling Foo.new.n
returns 0
Why does Foo.new.inc
raise an error? I can do Foo.new.n+=1
with no problem.
tldr; some form of self.n = x
must always be used to assign to a setter.
Consider that n += x
expands to n = n + x
where n is bound as a local variable because it appears on the left-hand side of an assignment. This "introduction" of a local variable counteracts the normal fall-back behavior of an implicit method call (e.g. n
-> self.n
) upon self.
Thus, since n
has not been assigned yet (but it is bound as a local variable now), the expression evaluates as n = nil + x
which is what causes the exception to be raised.
Use this
def inc
self.n += 1
end
or this
def inc
@n += 1
end
In your case, naked name "n" is interpreted as a local variable (which does not exist). You need to specify explicitly that it is a method (self.n
) or use underlying instance variable.
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