Menu
Coddy logo textTech

Multi-value when

Part of the Logic & Flow section of Coddy's Ruby journey — lesson 39 of 56.

A single when clause can match against any of several values, separated by commas. The branch fires if the subject equals any one of them.

day = "Sat"
kind = case day
       when "Sat", "Sun"                          then "weekend"
       when "Mon", "Tue", "Wed", "Thu", "Fri"  then "weekday"
       end
puts kind   # weekend

This is much cleaner than chaining || in an if/elsif.

You can also mix value types in one when: strings, ranges, regex patterns, they're all just things that respond to ===:

def describe(x)
  case x
  when 0, nil       then "empty"
  when 1..9         then "small"
  when 10..99       then "medium"
  when /^huge:/i    then "flagged huge"
  end
end

Pick whichever forms make each branch easy to read at a glance.

challenge icon

Challenge

Easy

Read a single character (one line of input). Use a case with multi-value when branches to print one of:

  • vowel: input is one of a, e, i, o, u (case-insensitive, convert input to lowercase first)
  • digit: input is one of 0..9 (use a range)
  • punctuation: input is one of ., ,, !, ?
  • other: anything else

Treat the input as a single-character string. Test the digit branch using a range like "0".."9".

For input E the output is vowel; for 7 it's digit; for ! it's punctuation.

Cheat sheet

A when clause can match multiple values separated by commas:

case day
when "Sat", "Sun" then "weekend"
when "Mon", "Tue", "Wed", "Thu", "Fri" then "weekday"
end

You can mix strings, ranges, and regex patterns in the same case:

case x
when 0, nil    then "empty"
when 1..9      then "small"
when /^huge:/i then "flagged huge"
end

Try it yourself

ch = gets.chomp

# TODO: case ch.downcase ... with multi-value when branches
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow