From my understanding, the following pieces of code are equivalent under
Ruby 1.9 and higher:
(1)
case
when x < y
foo
when a > b
bar
else
baz
end
(2)
if x < y
foo
elsif a > b
bar
else
baz
end
So far I would have always used (2), out of a habit. Could someone think
of a particular reason, why either (1) or (2) is “better”, or is it just
a matter of taste?
For once, the semantics suggests that
case
when x<y
end
is short for
case true
when x<y
end
Which is not true. (See code example below.) This is rather
non-intuitive and might lead to unexpected results if one is not aware
of this. Also, the usual usage of “case” statements is for checking
different values of a variable or expression; "if"s for checking whether
some condition is true. Using (1) instead of (2) could make the code
confusing for many programmers.
“case” is not equivalent to “case true”. The following code outputs
“foo”
“foobaz”
class TrueClass
def ===(rhs)
false
end
end
(1)
x = 1
y = 2
case
when x < y
p “foo”
when x > y
p “bar”
else
p “foobaz”
end
(3)
x = 1
y = 2
case true
when x < y
p “foo”
when x > y
p “bar”
else
p “foobaz”
end
Thanks a lot for taking the time to look at it. I hadn’t expected
anymore to get an answer to the question in this forum and crossposted
it at Stackoverflow
(Ruby: target-less 'case', compared to 'if' - Stack Overflow)
… sorry, forgot to mention it here.