Skip to content

Instantly share code, notes, and snippets.



Created Jun 1, 2016
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@suhlig 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