← Home · Ruby skill tree

An interactive Ruby lesson

Pattern matching

Pattern matching checks a value's structure and can capture parts of it. Start with Hashes and Conditions. This lesson uses hash patterns with case and in.

p displays a value. Predict the output, press Run, then open the expected output. Change one input and run again. Reset restores that example; Stop ends a running example.

The first Run downloads Ruby into your browser. JavaScript and a network connection are needed to run examples. Each run starts fresh, so keep the hash and its case expression together in the editor you run. The code and answers remain readable without JavaScript.

1. Match a literal value

case item checks item against each in pattern. { kind: :book } requires the symbol key :kind with the value :book. This nonempty partial hash pattern allows extra keys, so :price does not prevent a match. Predict the output.

Show expected output
"Book"

Try it: Change :book in the item hash to :pen. Predict which branch runs. If no in branch matches, else runs.

2. Capture a hash value

price: price requires the :price key and captures its value in the local variable price. A lowercase name in this pattern receives a value; it does not compare against an existing variable. Use the captured value inside the matching branch. Predict the number.

Show expected output
12

Try it: Change price: 12 in the hash to price: 7, then remove that entry. Predict the output for each edit.

3. Check the class and capture

Integer => price checks that the value matches Integer and captures it as price. The branch doubles that integer. Predict the result.

Show expected output
24

Try it: Change the hash value 12 to 12.5, then to "12". Predict why each takes the else branch.

4. Add a guard condition

The if price > 0 guard runs after the pattern matches. The branch runs only if the guard is true. The class check means a string or nil fails the pattern before Ruby tries the numeric comparison. Predict the output.

Show expected output
12

Try it: Change the hash price to 0, then -2, then "12". Explain whether the pattern or the guard prevents each match.

5. Choose the first eligible branch

Ruby tries the in branches in order and runs the first one whose pattern and guard succeed. Both patterns can match this book, but the guarded branch comes first. Predict which message appears.

Show expected output
"Expensive book"

Try it: Change the hash price to 5. Explain why the second branch runs after the first guard fails. Then swap the two in branches with their bodies and restore 12. Predict which message appears.

6. Reject extra keys with **nil

**nil requires that the hash have no keys beyond those listed in the pattern. The earlier nonempty partial hash patterns allow extra keys. Here **nil is a pattern constraint; it is separate from the call-site keyword expansion used in Keyword arguments. Hash patterns support symbol keys. Predict the number.

Show expected output
12

Try it: Add color: :red to the hash. Predict the output. Then remove that extra entry and replace the hash with { "kind" => :book, "price" => 12 }. Explain why string keys do not match these symbol keys.

If no branch matches and a case/in expression has no else, Ruby raises NoMatchingPatternError (or a subclass). Each example includes else to handle a failed match. Do not rely on captured variables after a failed pattern; use them only in the matching branch or its guard.

Practice on your own

Replace the code in the last editor with a program for these tasks. Predict the output, then run it.

  1. Create item = { kind: :book, price: 12 }.
  2. Use case/in to require exactly those symbol keys, a :book kind, and an integer price. Capture the price and add a guard that requires it to be positive.
  3. Display twice the price in the matching branch. In else, display "No valid book". Try zero, a string price, a different kind, and an extra key. Explain why each takes the fallback.
Show a solution and its output
item = { kind: :book, price: 12 }

case item
in { kind: :book, price: Integer => price, **nil } if price > 0
  p(price * 2)
else
  p("No valid book")
end

Output:

24

Ruby 4.0 reference: Pattern matching, including hash patterns, variable binding, guard clauses, and undefined behavior.

Return to pattern matching in the skill tree →