Skip to content

Instantly share code, notes, and snippets.

@unnu
Created February 3, 2012 12:04
Show Gist options
  • Save unnu/1729852 to your computer and use it in GitHub Desktop.
Save unnu/1729852 to your computer and use it in GitHub Desktop.
Why is foo returning nil in last line?
$ 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
@AndreeWille
Copy link

I would say because of foo is not set (if false). Object.foo returns 1

@slawosz
Copy link

slawosz commented Feb 3, 2012

@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

@unnu
Copy link
Author

unnu commented Feb 3, 2012

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