Created
February 3, 2012 12:04
-
-
Save unnu/1729852 to your computer and use it in GitHub Desktop.
Why is foo returning nil in last line?
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
$ irb | |
ruby-1.9.3-p0 :001 > def foo | |
ruby-1.9.3-p0 :002?> 1 | |
ruby-1.9.3-p0 :003?> end | |
=> nil | |
ruby-1.9.3-p0 :004 > foo | |
=> 1 | |
ruby-1.9.3-p0 :005 > if false | |
ruby-1.9.3-p0 :006?> foo = 2 | |
ruby-1.9.3-p0 :007?> end | |
=> nil | |
ruby-1.9.3-p0 :008 > foo | |
=> nil |
@dreewill but Object.foo
works only in irb
@unnu def foo
and foo
are in this same scope.
Simply
if false
foo = 2
end
is equivalent to
foo = 2
since in first case foo is not set, but is visible to interpreter, so is set to nil
But it's not true for instance variables for example.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I would say because of foo is not set (if false). Object.foo returns 1