# case…when or Hash#fetch [closed]

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.

## closed as off-topic by 200_success, hoffmale, Edward, Sᴀᴍ Onᴇᴌᴀ, t3chb0tOct 28 '18 at 21:04

This question appears to be off-topic. The users who voted to close gave this specific reason:

• "Lacks concrete context: Code Review requires concrete code from a project, with sufficient context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site." – 200_success, hoffmale, Edward, Sᴀᴍ Onᴇᴌᴀ, t3chb0t
If this question can be reworded to fit the rules in the help center, please edit the question.

• What task does this code accomplish? Please tell us, and also make that the title of the question via edit. Maybe you missed the placeholder on the title element: "State the task that your code accomplishes. Make your title distinctive.". Also from How to Ask: "State what your code does in your title, not your main concerns about it.". – Sᴀᴍ Onᴇᴌᴀ Oct 28 '18 at 18:48

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')