Ruby or and || operator evaluation

I wanted to define a variable in a way that allowed it either to be the result of a method or, if that method didn’t produce anything, a preset default value.

The method was written so that it would return nothing if a certain condition was not met. Here’s my experimental version:

def foo(argument) if argument.class == “”.class

return argument

end end

foo(“bar”) => “bar”

foo(123) => nil


Then I tested to see what happened if I wrote an expression to evaluate the output. I used the ‘or’ operator. It behaved as expected:

foo(“bar”) or “Nope!” => “bar”

foo(123) or “Nope!” => “Nope!”</typo:code>

But although when calling experimental method it does not seem to matter what kind of object is given on the right hand side of the evaluation…

foo(“bar”) or {“test”=>1, “me”=>2} => “bar”

foo(123) or {“test”=>1, “me”=>2} => {“me”=>2, “test”=>1}</typo:code>

… a similarly written expression in the real script would receive nil from a method, yet that returned value of nil would be chosen in preference to the object on the right hand side. Effectively:

foo(123) or {“test”=>1, “me”=>2} => nil</typo:code>

I changed the evaluation operator from ‘or’ to ‘||’, and it worked nicely, effectively:

foo(123) || {“test”=>1, “me”=>2} => {“me”=>2, “test”=>1}</typo:code>

Here is Programming Ruby 1/e on the or and || operators:

… both “or” and “||” evaluate to true if either operand is true. They evaluate their second operand only if the first is false. As with “and”, the only difference between “or” and “||” is their precedence.

Published on 23/06/2010 at 15:34 by Technophile, tags , , , ,

If you liked this article you can add me to Twitter

comment Ruby or and || operator evaluation

Trackbacks are disabled

Powered by Publify – Thème Frédéric de Villamil | Photo Glenn