In Ruby why won’t `foo = true unless defined?(foo)` make the assignment?

Apparently, ruby creates local variable at parse time setting them to nilso it is defined and this is done whether the code is executed or not.

When the code is evaluated at your first line, it doesn’t execute the assignment part since foo is set to nil. In the second line, because fooo has not been parsed yet, defined?returns nil letting the code inside the block execute and assign fooo.

As an example you can try this:

if false  
  foo = 43  
end  
defined? foo  
=> "local-variable"

This is taken from a forum post at ruby-forum.

Leave a Comment