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 (eg 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.