There was a weird thing I encountered in Ruby this morning, concerning the ternary operator. Here how it goes:
x = nil ? x : true
As known to all, x is set to true, no surprise there. Now, subsequentlyl running:
defined?(y)
=> nil
This answer would imply y has not been defined yet. However:
defined?(y) ? y : true
Returns true. No surprise again. The surprise comes here:
y = defined?(y) ? y : true
and what happens? y is set to nil!
But wait, there is more. Now since y is assigned, let’s work with z:
defined?(z)
#=> nil
Implying z is not defined yet.
z = defined?(z) ? false : true
And the suprise: z is set to false. I have no idea how that happens. Doing the same in an if block gives the same result.
z1 = if defined?(z1) then z1 else true end
Again z1 is set to nil.
z2 = if defined?(z2) then false else true end
This, too, gives me a surprise, as z2 is set to false. Now I was assuming the above expression to behave something like:
z3 = if nil then false else true end
where z3 gets assigned to true, considering the fact that defined? returned nil in all the above cases. This makes me believe that there is something special at work around defined? call, but I could find no information on it in Ruby documentation.
Btw. I tested the above on ruby 1.8.7 and 1.9.2
Ok. I think this explains it:
Apparently, whenever you assign something to a variable, ruby first initializes it to nil.