case Expressions
Prerequisites: Conditionals
A case expression compares one value against several possibilities
— a cleaner alternative to a long if/elsif chain.
Syntax
case value
when option1
# ...
when option2, option3
# ...
else
# none matched
end
Example
day = "Saturday"
case day
when "Saturday", "Sunday"
puts "Weekend!"
when "Friday"
puts "Almost weekend"
else
puts "Weekday"
end
Expected output
Weekend!
A single when can list several values separated by commas.
Matching ranges and types
when isn't limited to exact equality. It can match a range of
numbers or a class:
score = 84
grade = case score
when 90..100 then "A"
when 80...90 then "B"
when 70...80 then "C"
else "F"
end
puts grade
value = 3.5
case value
when Integer then puts "a whole number"
when Float then puts "a decimal number"
when String then puts "some text"
end
B
a decimal number
then lets you keep a short branch on one line. 80...90 (three dots)
means 80 up to but not including 90 — the Ranges lesson explains
the difference between .. and ....
Ruby 3 also has a more powerful case ... in form for pattern
matching on arrays and hashes, covered in Level 2.
Common mistakes
- Forgetting the
elsebranch, so an unexpected value silently producesnil.
Practice
Given a month number from 1 to 12, print the season (Northern
Hemisphere): 12, 1, 2 → winter; 3–5 → spring; 6–8 → summer; 9–11 →
autumn.
Show solution
month = 7
season = case month
when 12, 1, 2 then "winter"
when 3..5 then "spring"
when 6..8 then "summer"
when 9..11 then "autumn"
else "invalid month"
end
puts season
summer