Pattern matching in depth

Hashes and arrays

case/in matches the shape of a value and binds the parts in one step. A hash pattern names the keys it needs and ignores the rest; an array pattern names the positions and checks the length:

ruby -e 'case {a: 1}; in {a: Integer => n}; puts n; end'

1

ruby -e 'case [1, 2]; in [Integer => a, Integer => b]; p a + b; end'

3

The hash pattern is a subset match: extra keys are allowed. The array pattern matches the exact length unless it contains a splat. A pattern that does not match falls through to the next in or to else, and a case/in with no match and no else raises NoMatchingPatternError, unlike a case/when.

Find patterns

A splat on both sides matches a middle element, which is how a command line or a list is searched without an index:

ruby -e 'case [1, 2, 3]; in [*, 2, *]; puts :found; end'

found

The pattern binds nothing by default; name the parts with *before and *after when the surroundings matter. One splat is allowed per array pattern.

Guards

An if after a pattern adds a condition the shape cannot express. The pattern binds first, then the guard reads the bindings:

case [2, 1] in [a, b] if a > b puts "descending #{a}, #{b}" in [a, b] puts "ascending #{a}, #{b}" end

ruby guards.rb

descending 2, 1

A guard that raises propagates the error; a guard that is false moves to the next pattern. That is the same rule as a when with &&, with the bindings available.

deconstruct and deconstruct_keys

A class becomes matchable by defining one or both methods. deconstruct returns an array for array patterns and deconstruct_keys returns a hash for hash patterns:

class Point def initialize(x, y) @x = x @y = y end def deconstruct = [@x, @y] def deconstruct_keys(_keys) = { x: @x, y: @y } end point = Point.new(1, 2) case point in {x: Integer => x, y: Integer => y} puts x + y end case point in [x, y] puts "#{x}#{y}" end

ruby deconstruct.rb

3
12

The second line in the output is the same object through an array pattern. Struct and Data define both methods already, so a value object is matchable without code.

What to watch for

A hash pattern ignores extra keys; an array pattern does not ignore extra elements. That difference decides which one to use for data that may grow, and it is the first thing to check when a pattern that looks right does not match.

in without a case is a test on its own: value in {a: Integer} returns true or false, which is the version for a condition, while value => {a: Integer} raises NoMatchingPatternError when the shape does not match.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. How does a hash pattern such as {a: Integer} treat keys the pattern does not name?

    Answer

    It matches when those keys are present, and extra keys are allowed

    A hash pattern is a subset match, so a value with more keys still matches and the pattern reads the ones it names.

  2. What does this program print? value = {a: 1, b: 2} case value in {a: Integer} puts "keys: #{value.keys.size}" end

    Answer

    keys: 2

    The pattern asks for a only, and the extra b key does not stop it, so the value keeps both keys.

  3. What does this program print? case [1, 2] in [Integer] puts "one" in [Integer, Integer] puts "two" end

    Answer

    two

    Without a splat an array pattern checks the length, so the one-element pattern fails and the two-element one matches.

  4. What does this program print? case [1, 2, 3] in [*, 2, *] puts "middle" else puts "no" end

    Answer

    middle

    A splat on each side is the find pattern: it matches when some element of the array is 2.

  5. What does this program print? case [1, 2, 3] in [first, *rest] puts first p rest end

    Answer

    1 / [2, 3]

    The first binding takes one element and the named splat collects the remaining ones in an array.

  6. What does a guard after a pattern see?

    Answer

    The bindings the pattern has already made

    The pattern binds first and the if reads those names, which is why a guard can compare two parts of the value.

  7. What does this program print? case [1, 2] in [a, b] if a > b puts "descending" in [a, b] puts "ascending" end

    Answer

    ascending

    The shape matches but the guard is false, so the match moves on to the next pattern, which has no guard.

  8. Which methods must a class define to be matchable?

    Answer

    deconstruct for array patterns and deconstruct_keys for hash patterns

    The two methods return the array and the hash the patterns read, and a class can define one of them or both.

  9. What does this program print? class Pair def initialize(a, b) @a = a @b = b end def deconstruct = [@a, @b] end case Pair.new("x", "y") in [first, second] puts "#{first}#{second}" end

    Answer

    xy

    The array pattern calls deconstruct and binds the two elements, so the interpolation joins them.

  10. other holds {b: 1}. What does other => {a: Integer} do?

    Answer

    It raises NoMatchingPatternError

    The rightward form raises when the pattern does not match; the in form is the one that answers false.

Article author: Arthur Isaev