Skip to content

Instantly share code, notes, and snippets.

@suhlig
Created June 1, 2016 11:08
Show Gist options
  • Save suhlig/022ab73ad2d7c09cee8e5e235a00ff48 to your computer and use it in GitHub Desktop.
Save suhlig/022ab73ad2d7c09cee8e5e235a00ff48 to your computer and use it in GitHub Desktop.
Side effect of defined?
$ pry
pry> foo
NameError: undefined local variable or method `foo' for main:Object
pry> if defined?(foo)
* bar = 1
* end
=> nil
pry> if defined?(bar)
* puts "oops"
* end
oops
@suhlig
Copy link
Author

suhlig commented Jun 13, 2016

@avdi answered this in RubyTapas' Episode #412: Autovivification:

What we've run into here is a very special rule in how Ruby evaluates code. In a nutshell, the rule says that at a given line in the code, if there is any possibility that a local variable will exist, then that variable is guaranteed to always exist. Even if Ruby has to quietly assign it a nil value to ensure its existence.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment