Created
September 20, 2012 00:13
-
-
Save moxley/3753161 to your computer and use it in GitHub Desktop.
Weird Ruby Behavior
This file contains hidden or 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 MyClass | |
def value | |
"VALUE!" | |
end | |
def do_something | |
puts value # Outputs "VALUE!" | |
if false | |
value = nil # Should not execute | |
end | |
puts value # Outputs nothing | |
end | |
end | |
MyClass.new.do_something |
Local variable assignments in "keyword" blocks always result in that local variable being defined. If you did "for i in []" or "case...when false" it'd work, too. However, "[].each do" would not, nor would any other construct based around an explicit do/end block.
As I understand it, this is sort of an artifact of how local assignments inside "keyword" blocks are made inside the enclosing scope.
Shorter answer: if/case/while/etc. do not create a new scope for local variables, and local variables are defined in these constructs when they are parsed, not when they are executed.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
First call there is no definition of 'value' in the local scope, so it looks up to the instance, and finds the value method.
The interpreter then sees a definition of the 'value = nil' initializing 'value' as a local variable. The last puts outputs the value of 'value'. It's clearer what's happening if you change the 'value = nil' line to 'value = "value"' -- you still get