-
-
Save BanzaiMan/c615c9cd6fcf70ba7643 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Yes, this is correct.
You can also do:
def work(e)
self.i += e
end
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
It's pretty odd, isn't it?
i += e
seems to be the same asi = i + e
, which raises the same error, as opposed toi = self.i + e
, which works as expected.Also, this works, too:
It seems that Ruby assigns the variable early, unless it already is defined as a local variable, without checking methods.