Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 134 ยท Control Flow

case and when

Learn Ruby's case expression - matching values, ranges, classes, regexes and lambdas with ===, comma lists, then, else, and case without a subject.

When one value can lead to many different actions, a long chain of if and elsif gets noisy. Ruby's case expression is the tidy alternative: you name the value once, then list the situations you care about with when. Unlike the switch statement in many languages, case is far more powerful. It does not just compare for equality. It asks each when clause, "do you match this value?", and a clause can be a number, a range, a class, a regular expression or even a lambda.

Like if, case is an expression: it returns the value of the branch that ran, so you can assign the result straight to a variable. This lesson explains the basic form, the hidden === operator that makes it work, every kind of when you can write, and the pitfalls professionals watch for. If you have not met conditionals yet, read if, elsif, else and unless first.

The basic form

Ruby A first case expression

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Four things to notice:

  • case day evaluates day once. Each when is tested from top to bottom and the first match wins. There is no fall-through, so you never write break.
  • then lets you put the result on the same line. On separate lines you can leave then out.
  • when 6, 7 is a comma list. It means "6 or 7".
  • else is the fallback. If nothing matches and there is no else, the whole case returns nil.

Because case returns a value, name = case day ... end is common Ruby. Only the branch that matched is evaluated, so the other branches cost nothing.

The secret: === (case equality)

A when clause does not use ==. Ruby calls the case equality operator === with the when value on the left and your subject on the right:

Ruby
when_value === subject

So when 1..5 really runs (1..5) === day. Different classes define === in the way that makes sense for them. That one rule explains all the clever things case can do. You can call === yourself to see it.

Ruby Each class defines its own ===

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Notice the order. Integer === 5 is true, but 5 === Integer is false, because 5 === x just means 5 == x. That is why the thing you write after when is always the "pattern" and the thing after case is the value being tested.

What you can put after when

Literal values and comma lists

Strings, symbols and numbers compare by value. Use a comma for alternatives, which is easier to read than ||.

Ruby Strings and symbols

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Ranges

A range matches any value inside it, which makes grade tables and age brackets short. Floats work too because Range#=== uses comparison, not enumeration. Read more in Ranges.

Ruby Ranges and numeric brackets

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The beginless ...0 and endless 1.. ranges are handy for open-ended brackets.

Classes and modules

Because Class#=== is an is_a? test, case is the natural way to branch on the type of a value. Order matters: list the most specific class first, since Integer is also a Numeric.

Ruby Branching on type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Notice when nil: nil === nil is true, so it works as expected.

Regular expressions

A regexp when clause matches if the subject (which must be a string or symbol) contains a match. Captures land in the special variables $1, $2, and $~ as usual. See Regular Expressions for the syntax.

Ruby Routing text with regexes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Lambdas and any object with ===

A lambda (or any proc) matches when calling it with the subject returns a truthy value. That lets you express conditions inline without a subject-less case.

Ruby Lambdas as conditions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The first lambda that returns truthy wins, so 5000 is "big" even though it is also even.

Splat an array of options

You can expand an array into the when list with *, which is a clean way to keep the data separate from the logic.

Ruby Splatting a list into when

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

case without a subject

If you leave out the value after case, each when is treated as a plain condition and the first truthy one wins. It reads like an if/elsif chain, but lines up more neatly.

Ruby case with no subject

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Pitfalls and good habits

Forgetting the else

With no match and no else, case quietly returns nil. That is sometimes what you want, but when a missing case would be a bug, raise on purpose. Ruby even has a ready-made error for it.

Ruby Unknown value without else (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The first call prints nil with no complaint. The second ends with main.rb:14:in 'Object#strict_speed_limit': unknown road type: :country (ArgumentError). Failing loudly is usually better than carrying a nil into later code. (The newer case/in form, covered in Pattern Matching, raises NoMatchingPatternError on its own.)

Order and overlap

Only the first match runs. Put specific checks before general ones. A when Numeric placed above when Integer hides the second one forever.

when with a class vs. an instance

when String tests the class of the subject. when "String" compares to the literal text. Mixing the two up is a common beginner bug.

Performance note

For literal integers, symbols and strings, Ruby compiles case/when into a jump table, so a large case is a fast dispatch and usually faster than an if/elsif chain with the same checks. Do not contort your code for speed, but you can use case freely.

When to use case, and when not

  • Use case when you compare one value against many possibilities or categories.
  • Use if/elsif when the conditions involve different variables.
  • For a huge table of fixed key-to-value mappings, a hash ({ "start" => :starting }) is often clearer than a long case.
  • For taking apart arrays and hashes, prefer pattern matching.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which operator does a when clause use to test the subject?

    case calls when_value === subject. Many classes define === differently: ranges test membership, classes test is_a?, regexps test for a match.
  2. 2. What does a case expression return when no when matches and there is no else?

    A case/when with no match and no else simply evaluates to nil. Only case/in raises an error for a missing match.
  3. 3. In case 5000 with when 0..10 then when Integer, which when wins and why?

    Each clause is tested from the top. The range does not include 5000, so Ruby moves on, and Integer === 5000 is true. Only the first match runs.
  4. 4. How do you write a case that tests several conditions on different variables?

    Omitting the subject turns each when into a plain boolean condition, like an if/elsif chain.
  5. 5. What does when 6, 7 mean?

    A comma separates alternatives. The clause matches if any of the listed values matches.

Summary

  • case is an expression: it returns the value of the branch that ran, or nil if none did.
  • The first matching when wins, with no fall-through and no break.
  • A when clause calls pattern === subject: ranges test membership, classes test is_a?, regexps test matches, lambdas get called.
  • Use commas for alternatives, then for one-liners and *list to splat a list of options.
  • case with no subject works like an if/elsif chain.
  • Add an else that raises when an unknown value would be a bug.

Next: Pattern Matching