Ruby Gotcha of the Day

Okay, so in ruby:

>> nil or 'value'

=> "value"

because nil acts as false when used with boolean operators and any other object acts as true. Now let's assign the result to a temp variable a:

>> a = nil or 'value'

=> "value"
>> a
=> nil
Whoa?? Can you guess? In ruby the assignment operator is not special. It acts just like any other operator and does not have a lower precedence than the or operator. Therefore the expression

a = nil

executes first, which evaluates to nil, and assigns the value nil to a, and then the result nil is used in the expression nil or 'value'. Therefore to do what we intended we need to do:

>> a = (nil or 'value')

=> "value"
Wow! That is messed up.

blog comments powered by Disqus