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 # weekendThis 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
endPick whichever forms make each branch easy to read at a glance.
Challenge
EasyRead a single character (one line of input). Use a case with multi-value when branches to print one of:
vowel: input is one ofa, e, i, o, u(case-insensitive, convert input to lowercase first)digit: input is one of0..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"
endYou 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"
endTry it yourself
ch = gets.chomp
# TODO: case ch.downcase ... with multi-value when branches
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String Methods OverviewString InterpolationIterating Over StringsSplit and JoinRecap - String Weaver4Blocks, Procs & Lambdas
What is a Block?do..end vs BracesThe yield KeywordBlock ParametersProcs and LambdasRecap - Custom Iterator7Hashes Part 2
Hash.new with DefaultsIterating HashesNested HashesMerging and TransformingRecap - Frequency Counter10Project - Student Records
Project OverviewAdd Student5Enumerable Powerhouse
Select and RejectChaining MapReduce / Injectcount, all?, any?, none?group_by and partitionsort_by, min_by, max_byRecap - Data Pipeline8Advanced Decision Making
Case with Classes & RegexMulti-value whenTernary OperatorInline if / unlessRecap - Grade Classifier