Problem
I have the following method, which can be written in the following two ways: which one would you prefer, and why?
# version with case...when
def choose(value)
case value
when value < LOWER_LIMIT
'a'
when value > UPPER_LIMIT
'b'
else
'c'
end
# version with Hash#fetch
def choose(value)
{ (value < LOWER_LIMIT) => 'a',
(value > UPPER_LIMIT) => 'b'
}.fetch(true, 'c')
end
I personally find the first one more linear and readable.
Solution
I would have just gone for an if/else, this really isn’t a good use case for a case
statement and I’ve never seen anyone use a hash like that except for demonstration purposes:
def choose(value)
if value < LOWER_LIMIT
'a'
elsif value <= UPPER_LIMIT
'c'
else
'b'
end
end
or possibly using a ternary
def choose(value)
value < LOWER_LIMIT ? 'a' : value <= UPPER_LIMIT ? 'c' : 'b'
end
note that I find it easier to keep my conditions in ascending order.
If this is a common pattern I would consider extending ranges.
class Range
def case(value, less, in, more)
if value < first
less
elsif include?(value)
in
else
more
end
end
end
(LOWER_LIMIT..UPPER_LIMIT).case(value, 'a', 'c', 'b')