Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 134 ยท Control Flow

Pattern Matching

Learn Ruby pattern matching - case/in with arrays, hashes, find patterns, guards, the pin operator, deconstruct, deconstruct_keys, and the => and in operators.

Pattern matching lets you describe the shape of a value and pull pieces out of it in one step. Instead of checking data.is_a?(Hash), then data.key?(:name), then reading data[:name], you write one pattern such as { name: String => name } and Ruby does the testing and the assignment for you. It arrived in Ruby 2.7, became stable in 3.0 and 3.1, and in modern Ruby it is the cleanest way to handle parsed JSON, command lists, results from methods and small syntax trees.

The tool is case/in. It looks like case and when, but when compares with === against one value, while in can destructure arrays and hashes, bind variables, add guards, and raise an error if nothing matches. This lesson covers every pattern kind, the one-line forms => and in, and how your own classes can take part.

The basic form

Ruby Literals, alternatives and bindings

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.

Here is what each piece does:

  • in 0 is a value pattern. It matches when 0 === value, the same rule when uses, so ranges, classes and regexes all work too.
  • | separates alternatives.
  • => n binds the matched value to a new local variable n.
  • if n < 0 is a guard: the pattern matches only when the condition is also true.

The key difference from case/when: if no in matches and there is no else, Ruby raises NoMatchingPatternError instead of quietly returning nil. Silent mistakes become loud ones.

Array patterns

Square brackets match the elements of an array by position. A bare name matches anything and binds it. *rest collects the remainder.

Ruby Destructuring arrays

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.

Array patterns check the length too. [x] matches only one-element arrays. The unnamed * splat accepts any number of elements without binding them. The patterns are tried in order, so the specific ones come first.

Hash patterns

A pattern in braces (or just key: pairs) matches a hash that contains at least those keys, and the values must match their sub-patterns. Extra keys are ignored.

Ruby Destructuring hashes

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.

Shorthand like x: means "this key must exist; bind its value to a local variable called x". Only symbol keys are supported in hash patterns. Use **rest to capture the leftover pairs, or **nil to demand that there are no other keys.

Ruby Exact hashes with **nil and **rest

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.

Careful: the empty pattern {} matches only an empty hash, while [] matches only an empty array.

Nesting and the find pattern

Patterns nest as deeply as your data. A find pattern [*, pattern, *] searches an array for the first element (or run of elements) that matches.

Ruby Nested data and the find pattern

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.

In the last case the sub-pattern 10.. => big is an endless range that also binds the number. Find patterns cost a scan of the array, so use them for small collections.

Guards and the pin operator

A guard is if or unless after the pattern. The pin operator ^ says "do not bind a new variable here, match against the value this variable already has".

Ruby Pinning variables and expressions

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.

Without the pin, in expected would rebind expected to whatever value arrived and always match. The pin is how you compare with an existing variable. It also works with instance variables (^@limit) and globals.

A bare lowercase name in a pattern is always a binding, never a comparison. If you meant to compare with a variable, pin it: in ^expected.

What happens when nothing matches

Ruby NoMatchingPatternError (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 run ends with main.rb:3:in '<main>': {status: "weird"} (NoMatchingPatternError). For hashes the subclass NoMatchingPatternKeyError is raised when a key is missing. Both inherit from StandardError, so you can rescue them. Add an else branch when you want to handle unknowns yourself.

One-line forms: => and in

value => pattern destructures and raises if it does not match. value in pattern returns true or false and also binds variables. They are great for validating and unpacking without a full case.

Ruby Rightward assignment and boolean match

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.

Use => when the shape must be right (it documents your assumption and fails fast) and in when you want a yes/no answer.

Making your own classes matchable

Pattern matching calls two special methods. deconstruct returns an array for array patterns, and deconstruct_keys(keys) returns a hash for hash patterns. Struct and Data (see Struct and Data) define both for you.

Ruby Struct, Data and custom deconstruct

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.

Const[...] and Const(...) both check the class with === first and then apply the sub-patterns. deconstruct_keys receives the list of keys the pattern asked for (or nil when **rest is used), so an expensive object can compute only what is needed. Cache the result if deconstruct is costly, because a case may call it many times.

Good habits

  • Order patterns from most specific to most general.
  • Use else unless the NoMatchingPatternError is exactly what you want.
  • Prefer pattern matching to chains of is_a?, key? and dig when you inspect structured data such as parsed JSON.
  • Variables bound by a pattern are ordinary locals and stay visible after the case. Names starting with _ mean "ignore".
  • A variable may appear only once in a pattern, except names that start with an underscore.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens when no in clause matches and there is no else?

    Unlike case/when, case/in raises NoMatchingPatternError (or NoMatchingPatternKeyError for a missing hash key) when nothing matches.
  2. 2. In case x with in expected, where expected is an existing local variable, what happens?

    A bare name in a pattern is a binding. To compare with the existing value, pin it: in ^expected.
  3. 3. Which pattern matches the hash { name: "Ada", age: 36 }?

    Hash patterns match when the listed symbol keys are present with matching values. Extra keys are fine. String keys are not allowed in hash patterns, and an array pattern needs deconstruct.
  4. 4. What does result in { status: 200 } return?

    in is the boolean form. => is the form that raises when the pattern does not match.
  5. 5. Which methods make your own class work with array and hash patterns?

    Array patterns call deconstruct, hash patterns call deconstruct_keys. Struct and Data provide both.

Summary

  • case/in matches the shape of values: literals, ranges, classes, arrays, hashes and combinations of them.
  • A bare name binds, ^name compares with an existing variable, ^(expr) compares with an expression.
  • Array patterns check length. *rest collects the remainder, [*, x, *] is a find pattern.
  • Hash patterns need symbol keys, ignore extra keys, and support **rest and **nil.
  • Guards (if/unless) add extra conditions, | adds alternatives.
  • No match without else raises NoMatchingPatternError.
  • value => pattern destructures or raises, value in pattern returns a boolean.
  • Implement deconstruct and deconstruct_keys to make your own classes matchable.

Next: Loops