Thuta Learning
Ruby
IntermediateProgrammingBeginner

Case Statements

RubyLesson 1235 min

What you'll walk away with

  • Write case/when with several values per when, ranges and an else branch
  • Explain that when uses === and use it with classes, regexes and lambdas
  • Use case as an expression and predict what it returns when nothing matches
  • Write simple case/in patterns for hashes and arrays, with guards, and know when NoMatchingPatternError is raised

Explain it simply

Explain it simply

Imagine sorting parcels at a post office. One clerk reads each address and drops the parcel into the right bin: local, national, international. A case statement is that clerk: it looks at one value and sends the program down exactly one path, depending on what the value is.

It does the same job as a long if/elsif chain, but the subject is written once at the top and every path starts with a short when line. That makes menus, status codes, grades and user roles much easier to read and to extend.

Problem → Why → Solution

The problem: an if/elsif chain repeats the subject on every line

Take HTTP status codes. A first attempt uses if/elsif and repeats code == over and over, as in code == 200 || code == 201 || code == 204. The repeated subject makes every line noisy, and it is easy to slip, for example by typing a single = so that the comparison becomes an assignment, or by forgetting a code such as 202.

The chain also hides the intent. You have to read every condition to see that the lines are really just a table from codes to labels.

label.rb
def label(code)
  if code == 200 || code == 201 || code == 204
    "success"
  elsif code == 301 || code == 302
    "redirect"
  elsif code >= 400 && code < 500
    "client error"
  elsif code >= 500
    "server error"
  else
    "unknown"
  end
end

What would a better shape look like?

The subject, code, never changes, and only the thing it is compared with does. A case statement lets you write the subject once and list the values, ranges and groups you care about, so the code reads like the table it really is. You also gain a rule you can rely on: the first matching when wins, with no fall-through to worry about.

Core concept: every when is tested with ===

A case expression compares one value, the subject, against a list of when clauses from top to bottom. The first when that matches wins, Ruby runs its body and leaves the whole case, and there is no fall-through, so you never write break. If nothing matches and there is an else, the else runs; with no else the case simply gives nil.

The comparison is not ==. Each when value is tested with the === operator, called case equality, in the form when_value === subject. For most values === means ordinary equality, so when "B" matches the string "B". The difference shows with other kinds of values, which is what makes case so flexible. The table lists what === does for the common ones.

when valueWhat === meansExample
A number or stringequal to the subjectwhen 200, when "yes"
A Rangethe subject lies within it (cover?), so 2.5 matches 1..9when 90.. or when 1..9
A classthe subject is an instance of itwhen Integer, when String
A Regexpthe string matches the patternwhen /\A\d+\z/
A lambdacalling it with the subject returns truewhen ->(n) { n > 100 }

Because === is just a method, Ruby also lets a when list several values separated by commas (when 200, 201, 204), and spreads an array with a splat (when *WEEKEND). case is an expression, so you can assign it, as in label = case score ... end, and a one-line branch can use then. A case with no subject at all behaves like a tidy if/elsif chain, where every when holds its own condition.

Order matters exactly as it does in an if chain. Put the specific values before the general ones, for example when 0 before when Integer, because the first match wins. The same === protocol powers rescue clauses, which is how rescue ArgumentError catches an error, and Enumerable#grep, which keeps the items for which pattern === item is true, as in ["a", 1].grep(String).

Mental model: ask each when in turn
  1. Evaluate the case subject once
  2. Test when_value === subject in order
  3. The first true when runs, then case ends
  4. No match: else, or nil without else

A case asks "is it this, or this, or this?" in turn, runs the first when that answers yes, and stops.

General pattern

ruby
result = case subject
         when value_a, value_b then result_a   # comma: either value
         when 1..9 then result_b                # range
         when SomeClass then result_c           # class check
         when /pattern/ then result_d           # regex match
         else default_result
         end

case data                       # pattern matching (Ruby 3+)
in { key: Type => name } then use(name)
end

The first half is case/when: each when is tested with === and the result is assigned to result. The second half, case/in, checks the shape of a value and captures the parts you want under names (Ruby 3 and later).

Example: turning a grade into a message

This example turns a letter grade into a message. The subject, grade, is written once at the top, and each when holds one candidate value. Ruby tests them from top to bottom, runs only the first match and ignores the rest.

With grade = "B" the second when matches, so "Good job!" is printed and the else branch never runs. Change grade to "Z" and run it again to see why the else is needed.

ruby
grade = "B"

case grade
when "A"
  puts "Excellent!"
when "B"
  puts "Good job!"
when "C"
  puts "Keep practicing."
else
  puts "Invalid grade."
end

Code breakdown

  1. The subjectgrade = "B"

    The value to test. Every when in the case is compared with it.

  2. casecase grade

    grade is evaluated once and compared with each when in turn. You do not repeat the subject on every line as an if chain would.

  3. No matchwhen "A"

    "A" === grade is false for "B", so it is skipped. For strings === is ordinary equality, so the match is exact and case-sensitive.

  4. Matchwhen "B"

    This when matches, so Ruby runs the puts below it and leaves the case. No break is needed, and the whens after it are not examined.

  5. Fallbackelse

    It catches values such as "Z" that no when matches and prints Invalid grade. Remove the else and a non-matching grade would do nothing, silently.

You should see
Good job!

=== in action: ranges, classes, regexes and lambdas

The describe method below sorts a mixed bag of values using a different === in each when. Mind the order too: when 0 and when 1..9 come before when Integer, which is why 7 is a "single digit" and only 250 is a "bigger integer".

describe.rb
def describe(value)
  case value
  when nil then "nothing"
  when 0 then "zero"
  when 1..9 then "single digit"
  when Integer then "bigger integer"
  when Float then "decimal"
  when /\A\d+\z/ then "digits inside a string"
  when String then "text"
  when ->(v) { v.respond_to?(:each) } then "something you can loop over"
  else "unknown"
  end
end

[nil, 0, 7, 250, 12.5, "123", "hello", [1, 2], :sym].each do |value|
  puts "#{value.inspect}: #{describe(value)}"
end

The output is nil: nothing, 0: zero, 7: single digit, 250: bigger integer, 12.5: decimal, "123": digits inside a string, "hello": text, [1, 2]: something you can loop over and :sym: unknown. Notice that "123" meets the regex when before the String when, so swapping their order would change the answer. The lambda when passes v into the lambda and matches only when it returns true, which is why [1, 2] matches: it responds to each.

case as an expression, comma lists and the subject-less case

The status_text method below rewrites the HTTP problem with case. Single numbers are grouped with commas, the range 400..499 covers client errors, and the endless range 500.. covers everything above it. The second part tries a case without a subject and finally shows that a case with no matching when gives nil.

status_text.rb
def status_text(code)
  case code
  when 200, 201, 204 then "success"
  when 301, 302 then "redirect"
  when 400..499 then "client error"
  when 500.. then "server error"
  else "unknown"
  end
end

[204, 302, 404, 503, 100].each { |code| puts "#{code}: #{status_text(code)}" }

temperature = 15
mood = case
       when temperature < 10 then "cold"
       when temperature < 20 then "mild"
       else "hot"
       end
puts mood

result = case 5
         when 1 then "one"
         end
p result

The first five lines of output are 204: success, 302: redirect, 404: client error, 503: server error and 100: unknown, followed by mild and nil. The case form is shorter and cleaner than the if chain, and code == never has to be repeated. Notice that the result is stored straight into a variable (mood = case ...), which works because case is an expression.

Pattern matching with case/in

Pattern matching, available in Ruby 3.0 and later, does more than test equality with ===: it checks the shape of a value and names the parts you want in the same step. It is most useful for taking hashes and arrays apart. The table shows the main differences between case/when and case/in.

Questioncase/whencase/in
What is comparedwith ===structure and values (patterns)
Can it take hashes and arrays apartnoyes, and it binds names
Nothing matches and no elsereturns nilraises NoMatchingPatternError
events.rb
def handle(event)
  case event
  in { type: "click", x: Integer => x, y: Integer => y }
    "click at #{x},#{y}"
  in { type: "key", key: String => key } if key.size == 1
    "typed #{key}"
  in { type: "key", key: }
    "special key #{key}"
  in [first, *rest]
    "list: #{first} then #{rest.size} more"
  in nil
    "nothing"
  end
end

p handle({ type: "click", x: 3, y: 4 })
p handle({ type: "key", key: "a" })
p handle({ type: "key", key: "Enter" })
p handle([1, 2, 3])
p handle(nil)

begin
  handle("zz")
rescue NoMatchingPatternError => e
  puts "#{e.class}: #{e.message}"
end

The output is "click at 3,4", "typed a", "special key Enter", "list: 1 then 2 more", "nothing", followed by NoMatchingPatternError: zz. x: Integer => x accepts :x from the hash only if it is an Integer and names it x, if key.size == 1 is a guard, and the short form key: captures the value into a variable called key. "zz" matches no pattern and there is no else, so NoMatchingPatternError is raised.

In real projects

Where this shows up in real projects

case is everywhere code has to dispatch on a value. A command-line tool decides what to do with the first word the user types, a web router maps a path to a handler (often with a regex), a billing system turns a status symbol into text, and a parser sorts tokens by class. Handling HTTP statuses, as in this lesson, is such a common job that you will find versions of it in most web codebases.

Pattern matching is growing in the same places. When a JSON event arrives as a hash, case/in can check its shape, bind the fields you need and reject everything else in one statement, replacing a pile of key? and is_a? checks. Because rescue clauses and Enumerable#grep use the same === protocol, learning it once pays off in error handling, filtering and test code too.

Common mistakes

Common mistakes

1. Expecting case-insensitive or type-flexible matches

when "yes" does not match "Yes" or the symbol :yes, because === is plain equality for strings and symbols. Normalize the subject on the case line itself, for example case input.strip.downcase.

2. Forgetting that no else means nil

In case/when, when no when matches and there is no else, the case gives nil without any error, and if you use the result a nil error can appear later. Add an else, and for unexpected values raise a clear error in it.

3. Putting a general when before a specific one

In case 15 with when 1..10, when 10..20 and when 15, you get "b" and never reach 15, because 10..20 matches first. The first match wins, so put the narrowest, most specific when at the top.

4. Writing a comparison inside when

Writing when > 5 is a syntax error, because a when takes a value, not an operator. Use a range (when 6..), a lambda (when ->(n) { n > 5 }) or a case with no subject.

5. Forgetting that case/in raises when nothing matches

case/when gives nil, but case/in with no else raises NoMatchingPatternError when no pattern fits. That error cannot be ignored, which is often an advantage, but for unexpected input add an else or handle the error deliberately.

Best practices

Best practices

  • Normalize the subject once, with strip and downcase, before the case.
  • Always include an else when the result is used, or raise a clear error in it.
  • Put specific values before general classes and ranges.
  • For a plain value-to-value lookup, a Hash read with fetch, such as STATUS_LABELS.fetch(code), can be shorter than a case.

Mini challenge

Mini challenge: a tiny command router

Write run_command(line), which takes one line typed by a user and returns text describing what to do. Combine exact words, a comma list and regex whens in a single case.

  • Clean the line with strip and downcase before the case (" Quit " must become quit)
  • "help" or "?" returns "help text", and "quit" or "exit" returns "bye"
  • A command such as "add tea" matches a regex and returns "added tea", and "delete 42" returns "deleted 42" (use $1 from the regex)
  • Everything else returns "unknown: <text>"
router.rb
def run_command(line)
  # TODO: clean the input with strip and downcase
  # TODO: "help" or "?" -> "help text"; "quit" or "exit" -> "bye"
  # TODO: "add <word>" -> "added <word>" with a regex and $1
  # TODO: "delete <number>" -> "deleted <number>"
  # TODO: anything else -> "unknown: <text>"
end

# TODO: run it for "help", " Quit ", "add tea", "delete 42" and "dance"

Expected: help text bye added tea deleted 42 unknown: dance

Show hint

In case text, when /\Aadd (\w+)\z/ puts the captured word in $1 when it matches. \A and \z stand for the start and end of the string, so extra text such as "add tea please" is rejected. The comma list is when "help", "?".

Show solution
router.rb
def run_command(line)
  text = line.strip.downcase

  case text
  when "help", "?" then "help text"
  when "quit", "exit" then "bye"
  when /\Aadd (\w+)\z/ then "added #{$1}"
  when /\Adelete (\d+)\z/ then "deleted #{$1}"
  else "unknown: #{text}"
  end
end

["help", " Quit ", "add tea", "delete 42", "dance"].each do |line|
  puts run_command(line)
end

Quick quiz 1 / 3

Which when clause matches the string "42"?

Quick quiz 2 / 3

What does a case/when expression return when no when matches and there is no else?

Quick quiz 3 / 3

In case 15, where when 1..10 gives "a", when 10..20 gives "b" and when 15 gives "c", what is the result?

What to remember

  • case compares the subject with each when from top to bottom and runs only the first match; no break is needed.
  • Every when uses ===, so ranges, classes, regexes and lambdas all work; with no match, case gives nil.
  • case is an expression you can assign; put specific whens before general ones and do not forget else.
  • case/in takes hashes and arrays apart and names the pieces, and raises NoMatchingPatternError when nothing matches.

Official Ruby Documentation — Ruby Documentation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Case Statements | Thuta Learning