-
-
Save chriseppstein/3eecf49d51155b5ccdc9 to your computer and use it in GitHub Desktop.
foo = 1 unless defined?(foo) | |
foo #=> nil | |
FOO = 1 unless defined?(FOO) | |
FOO # => 1 |
miah
commented
May 29, 2014
Right, they both behave the same if already defined. My WTF is about how they behave differently when not already defined.
Merely mentioning a local variable defines it in that scope, even if that code would never execute.
if false
a = 1
end
p defined?(a)
$ ruby -v local.rb
ruby 2.1.1p76 (2014-02-24 revision 45161) [x86_64-darwin13.0]
"local-variable"
@chriseppstein Yeah, I can see how this would be confusing. Local variables are considered "defined" but not yet assigned once they're first encountered in source, since that's the point at which storage must be available for them in local scope. Constants are not considered defined until actually assigned, since that's the point at which we actually need storage for them.
I don't think it's inconsistent, since constants are essentially stored in global state, while local variables are only stored in per-call state. Constants "can't" (shouldn't) be reassigned. A method's local variables can't be accessed outside that method body (unless shoved into the heap). They're very different.