Case Expressions
Ruby's answer to switch statements -- more powerful than most, thanks to the === operator working behind the scenes.
2 min read
case is Ruby's multi-branch conditional, similar to switch in other languages but considerably more flexible because of how it matches values.
The basic form
grade = "B"
case grade
when "A"
puts "Excellent"
when "B", "C"
puts "Good"
when "D"
puts "Needs improvement"
else
puts "Invalid grade"
endMultiple values in one when ("B", "C") match if the value equals any of them — no fall-through, no break needed like in C-family switch statements. Only the first matching branch runs.
case as an expression
Like if, case returns a value:
message = case grade
when "A" then "Excellent"
when "B", "C" then "Good"
else "Needs improvement"
end
puts messagethen after the when condition lets you write the branch on the same line, which is handy for short cases like this.
The real power: === and pattern-like matching
case/when doesn't use == to compare — it uses ===, and different classes define === to mean different things. This is what makes case work with ranges, classes, and regular expressions, not just exact values:
def describe(value)
case value
when 1..9
"single digit"
when 10..99
"double digit"
when String
"a string: #{value}"
when /^\d+$/
"a numeric string"
when nil
"nothing"
else
"something else"
end
end
describe(5) # "single digit"
describe(42) # "double digit"
describe("hello") # "a string: hello"
describe(nil) # "nothing"1..9 is a Range, and Range#=== checks whether the value falls inside it. String is a class, and Class#=== checks whether the value is_a? that class. A regex's === checks for a match. This is genuinely different from most languages' switch, which typically only supports exact equality — Ruby's case is closer to lightweight pattern matching.
case without a subject
You can also omit the value after case and put full boolean conditions in each when — this is really just a tidier if/elsif chain:
case
when age < 13
puts "child"
when age < 20
puts "teenager"
else
puts "adult"
endWhen to reach for case over if/elsif
Once you have more than two or three branches checking the same variable against different values or types, case reads more clearly than a long if/elsif chain — the repeated variable name disappears, and each condition lines up visually under when. For a single yes/no branch, plain if is still the better, simpler choice.
Test what you just learned
4 quick questions. Get all of them right to unlock the next lesson.
You can take the quiz without an account — logging in just lets your result count toward your progress.