I was expecting the following snippet:
var = "Not Empty" unless defined? var
var # => nil
to return "Not Empty"
, but I got nil
. Any insight into why this is happening?
I was expecting the following snippet:
var = "Not Empty" unless defined? var
var # => nil
to return "Not Empty"
, but I got nil
. Any insight into why this is happening?
Local variables are defined (as
nil
) at the point they are parsed. Definition ofvar2
precedes the condition. That makesvar2
defined even when if the assignment is not executed. Then, the condition evaluates thatvar2
is defined, which retains the valuenil
forvar2
.This is one of the only moments in Ruby I would call actual WTFs.
You have to use
With the postfix syntax, the interpreter will internally
nil
-ify the value so it can reason about the variable, thus making it defined before the check is done: