When it is in fact not defined, it gets the value nil just because it was “touched”:
$ irb
ruby-1.9.2-p0 > foo = true if !defined? foo
=> nil
ruby-1.9.2-p0 > foo
=> nil
ruby-1.9.2-p0 > if !defined? bar
ruby-1.9.2-p0 ?> bar = true
ruby-1.9.2-p0 ?> end
=> true
ruby-1.9.2-p0 > bar
=> true
so the if … end works as expected, but foo = true if ... doesn’t.
Ruby defines a local variable just before executing a line containing an assignment, so
defined?(foo)will always betruefor the one-liner.Another example showing that local variables are defined before any part of the line are executed: