HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyCritical

Case statement with multiple values in each 'when' block

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
withstatementblockmultipleeachwhenvaluescase

Problem

The best way I can describe what I'm looking for is to show you the failed code I've tried thus far:
case car
when ['honda', 'acura'].include?(car)
# code
when 'toyota' || 'lexus'
# code
end


I've got about 4 or 5 different when situations that should be triggered by approximately 50 different possible values of car. Is there a way to do this with case blocks or should I try a massive if block?

Solution

In a case statement, a , is the equivalent of || in an if statement.

case Expression in Ruby
case car
when 'toyota', 'lexus'
puts 'brand is part of the Toyota Motor Corporation'
else
puts 'some other brand'
end

# NOTE: You may use
then after the when condition.
# It is frequently used to place the body of the
when on a single line.
case car
when 'toyota', 'lexus' then puts 'brand is part of the Toyota Motor Corporation'
else puts 'some other brand'
end

Context

Stack Overflow Q#10197254, score: 902

Revisions (0)

No revisions yet.