Skip to content

Instantly share code, notes, and snippets.

@BanzaiMan
Created May 16, 2015 14:15
Show Gist options
  • 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)
@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