Skip to content

Instantly share code, notes, and snippets.

@BanzaiMan
Created May 16, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save BanzaiMan/c615c9cd6fcf70ba7643 to your computer and use it in GitHub Desktop.
Save BanzaiMan/c615c9cd6fcf70ba7643 to your computer and use it in GitHub Desktop.
class X
attr_accessor :i
def initialize
@i = 0
end
def work(e)
i += e
end
end
x = X.new
x.work 5 # => undefined method `+' for nil:NilClass (NoMethodError)
@svenfuchs
Copy link

It's pretty odd, isn't it?

i += e seems to be the same as i = i + e, which raises the same error, as opposed to i = self.i + e, which works as expected.

Also, this works, too:

  def work(e)
    i = self.i
    i += e
  end

It seems that Ruby assigns the variable early, unless it already is defined as a local variable, without checking methods.

@halorgium
Copy link

Yes, this is correct.

You can also do:

def work(e)
  self.i += e
end

@BanzaiMan
Copy link
Author

The wise man said: https://twitter.com/roidrage/status/599580807993434113

Ruby uses local scope by default and creates the variable i in the function afair. Needs to be self.i or @i with assignments.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment