1 min read

TIL: Matching Multiple Values in a Case Statement

Matching more than one value in a case statement

This is more a 'Today, I remembered'. This is one I keep forgetting.

You can easily match more than one value in a Ruby case statement.

colours = [:red, :green, :blue]
colour = colours.sample

case colour
when :red, :green
  puts 'red or green'
when :blue
  puts 'blue'
end

You can use the splat operator too:

colours = [:red, :green, :blue]
flavours = [:sweet, :sour, :bitter, :umami]
something = (colours + flavours).sample

case something
when *colours
  puts 'a colour'
when *flavours
  puts 'a flavour'
end