Ruby Case/When
When you compare one value against many possibilities, a long if/elsif chain becomes noisy. Ruby's case/when statement is cleaner — and much more powerful than a classic switch, because each when can be a value, a list, a range, a class, a regular expression or even a lambda.
Basic case/when
day = "sat"
case day
when "mon", "tue", "wed", "thu", "fri"
puts "Work day"
when "sat", "sun"
puts "Weekend!"
else
puts "Not a day"
endWeekend!
- A
whencan list several values separated by commas. - There is no fall-through and no
breakneeded: only the first matching branch runs. elsehandles everything else (it is optional; without it,casereturnsnil).
case is an expression
Like if, case returns a value. Use then to keep short branches on one line:
def http_status(code)
case code
when 200 then "OK"
when 301, 302 then "Redirect"
when 404 then "Not Found"
when 500 then "Server Error"
else "Unknown (#{code})"
end
end
[200, 302, 404, 418].each { |c| puts "#{c}: #{http_status(c)}" }200: OK
302: Redirect
404: Not Found
418: Unknown (418)
Ranges
Because when uses the === operator, a range matches any value it contains:
def bmi_category(bmi)
case bmi
when ...18.5 then "underweight"
when 18.5...25 then "normal"
when 25...30 then "overweight"
else "obese"
end
end
[17.2, 22.0, 27.9, 31.4].each { |b| puts "#{b}: #{bmi_category(b)}" }17.2: underweight
22.0: normal
27.9: overweight
31.4: obese
...18.5 is a "beginless" range: everything below 18.5.
Classes
A class in a when matches instances of that class — handy when a method accepts different kinds of input:
def describe(value)
case value
when Integer then "an integer"
when Float then "a float"
when String then "a string of length #{value.length}"
when Array then "an array of #{value.size} items"
when nil then "nothing at all"
else "something else (#{value.class})"
end
end
[42, 1.5, "hey", [1, 2], nil, :sym].each { |v| puts describe(v) }an integer
a float
a string of length 3
an array of 2 items
nothing at all
something else (Symbol)
Regular expressions and lambdas
def classify(input)
case input
when /\A\d+\z/ then "number"
when /\A[\w.]+@[\w.]+\z/ then "email"
when ->(s) { s.length > 10 } then "long text"
else "short text"
end
end
puts classify("2025")
puts classify("lea@example.com")
puts classify("a fairly long sentence")
puts classify("hi")number
email
long text
short text
A lambda in a when is called with the value, and the branch matches if it returns something truthy.
case without a value
If you leave out the value after case, each when is simply a condition — a tidy alternative to if/elsif:
temp = 7
rain = true
advice = case
when temp < 0 then "Stay inside"
when rain then "Take an umbrella"
when temp > 25 then "Sunscreen!"
else "Enjoy the day"
end
puts adviceTake an umbrella
What when matches with
when value |
Matches when… | Example |
|---|---|---|
| Plain value | value == x |
when "red" |
| Range | the range includes x | when 1..9 |
| Class/module | x is an instance | when String |
| Regexp | the pattern matches x | when /^\d+$/ |
| Lambda/proc | it returns truthy for x | when ->(n) { n.even? } |
| Several, comma-separated | any of them matches | when :a, :b |
Note: Ruby 3 also has
case/infor pattern matching, which can destructure arrays and hashes. It has its own lesson in the Advanced section.
Test yourself
Which operator does case/when use to compare?
=====eql?equal?
Do you need break at the end of each when branch?
- Yes, otherwise it falls through
- No, only the first matching branch runs
- Only in the last branch
- Only when using ranges
What does case 7 when 1..5 then "low" when 6..10 then "high" end return?
- "low"
- "high"
- nil
- 7