Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: method inexplicably overwritten and set to nil

If I execute this ruby code:

def foo
  100
end

p defined?(foo), foo
if false
  foo = 200
end
p defined?(foo), foo

The output I get is:

"method"
100
"local-variable"
nil

Can someone explain to me why foo is set to nil after not executing the if? Is this expected behavior or a ruby bug?

like image 250
bmesuere Avatar asked Dec 14 '11 14:12

bmesuere


1 Answers

Names on the left hand side of assignments get set to nil, even if the code can't be reached as in the if false case.

>> foo
NameError: undefined local variable or method `foo' for main:Object
...
>> if false
..   foo = 1
..   end #=> nil
>> foo #=> nil

When Ruby tries to resolve barewords, it first looks for local variables (there's a reference to that in the Pickaxe book, which I can't seem to find at the moment). Since you now have one called foo it displays nil. As Mischa noted, the method still can be called as foo().

like image 55
Michael Kohl Avatar answered Oct 03 '22 20:10

Michael Kohl