Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby increment (+=) raises error undefined method '+' for nil:NilClass

Tags:

ruby

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.

like image 863
Davd_R Avatar asked Oct 24 '13 04:10

Davd_R


2 Answers

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.

like image 148
user2864740 Avatar answered Oct 31 '22 09:10

user2864740


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.

like image 36
Sergio Tulentsev Avatar answered Oct 31 '22 10:10

Sergio Tulentsev