It's critical to emphasize the comma (,
) in a when
clause. It acts as an ||
of an if
statement, that is, it does an OR comparison and not an AND comparison between the delimited expressions of the when
clause. See the following case statement:
x = 3
case x
when 3, x < 2 then 'apple'
when 3, x > 2 then 'orange'
end
=> "apple"
x
is not less than 2, yet the return value is "apple"
. Why? Because x
was 3 and since ',`` acts as an
||, it did not bother to evaluate the expression
x < 2'.
You might think that to perform an AND, you can do something like this below, but it doesn't work:
case x
when (3 && x < 2) then 'apple'
when (3 && x > 2) then 'orange'
end
=> nil
It doesn't work because (3 && x > 2)
evaluates to true, and Ruby takes the True value and compares it to x
with ===
, which is not true, since x
is 3.
To do an &&
comparison, you will have to treat case
like an if
/else
block:
case
when x == 3 && x < 2 then 'apple'
when x == 3 && x > 2 then 'orange'
end
In the Ruby Programming Language book, Matz says this latter form is the simple (and infrequently used) form, which is nothing more than an alternative syntax for if
/elsif
/else
. However, whether it is infrequently used or not, I do not see any other way to attach multiple &&
expressions for a given when
clause.