case / when (Ruby)

case/when is Ruby's classic multi-branch conditional, like a switch. Each when uses the === operator, so it can match values, ranges, classes, and regexes, returning the value of the matching branch.

Ruby

A case expression compares a subject against when clauses using the === case-equality operator, which is what makes it flexible: a Range's === checks membership (when 1..10), a Class's === checks instance-of (when Integer), and a Regexp's === checks a match. It returns the matching branch's value, so you can assign its result.

There's no fall-through and no break needed — only the first matching when runs. A when can list several values (when 1, 2, 3), and an optional else handles the rest. A subject-less case (case; when condition) acts like an if/elsif chain.

For matching the structure of arrays and hashes (destructuring) rather than testing values, use the newer case/in pattern matching instead. case/when remains the go-to for value, range, and type dispatch.

Syntax

case value
when 1..10 then "small"
when Integer then "other int"
else "?"
end

Examples

Ruby

def classify(x)
  case x
  when 0 then "zero"
  when 1..9 then "small"
  when Integer then "big"
  else "not an integer"
  end
end

puts classify(5)
puts classify(100)
puts classify("hi")

Output:

small
big
not an integer

Learn it in a lesson

See also

Back to the Dictionary