TExcelTAD
Home › Ruby › Ruby Pattern Matching

Ruby Pattern Matching

Ruby 3 introduced pattern matching with case/in. Where case/when compares a value, case/in checks its shape — is it an array of two items? a hash with a :status key? — and pulls out the parts you need into variables in one step. It is perfect for working with JSON-like data, results and messages.

A first example

ruby · try it yourself
def describe(point)
  case point
  in [0, 0] then "origin"
  in [x, 0] then "on the x-axis at #{x}"
  in [0, y] then "on the y-axis at #{y}"
  in [x, y] then "at (#{x}, #{y})"
  end
end

puts describe([0, 0])
puts describe([5, 0])
puts describe([0, -2])
puts describe([3, 4])
origin
on the x-axis at 5
on the y-axis at -2
at (3, 4)

A pattern like [x, 0] means: "an array with exactly two elements, the second one equal to 0 — bind the first one to x".

Hash patterns

Hash patterns match some keys (extra keys are allowed) and bind values:

ruby · try it yourself
def handle(event)
  case event
  in {type: "click", x:, y:}
    "click at #{x},#{y}"
  in {type: "key", key: "Enter"}
    "submit"
  in {type: "key", key:}
    "typed #{key}"
  in {type:}
    "unknown event #{type}"
  end
end

puts handle({type: "click", x: 10, y: 20, button: 1})
puts handle({type: "key", key: "Enter"})
puts handle({type: "key", key: "a"})
puts handle({type: "scroll", delta: 3})
click at 10,20
submit
typed a
unknown event scroll

x: on its own is shorthand for "the key :x, bound to a variable named x". Hash patterns only work with symbol keys.

NoMatchingPatternError

If no branch matches and there is no else, Ruby raises an error — a safety net that tells you about unexpected data:

ruby · try it yourself
begin
  case {status: "weird"}
  in {status: "ok"} then puts "fine"
  end
rescue NoMatchingPatternError => e
  puts "#{e.class}: #{e.message}"
end
NoMatchingPatternError: {status: "weird"}: "ok" === "weird" does not return true

Types, ranges and alternatives

Any value that works with === can be part of a pattern, and | means "or":

ruby · try it yourself
def classify(value)
  case value
  in Integer | Float => n if n.negative? then "negative number"
  in 0 then "zero"
  in Integer => n then "integer #{n}"
  in Float then "float"
  in String => s if s.empty? then "empty string"
  in String then "string"
  in [] then "empty array"
  in [_, *] then "non-empty array"
  in nil then "nil"
  end
end

[-4, 0, 12, 1.5, "", "hi", [], [1, 2], nil].each { |v| puts "#{v.inspect} -> #{classify(v)}" }
-4 -> negative number
0 -> zero
12 -> integer 12
1.5 -> float
"" -> empty string
"hi" -> string
[] -> empty array
[1, 2] -> non-empty array
nil -> nil
  • Integer => n checks the type and binds the value to n.
  • if ... after a pattern is a guard: an extra condition.
  • _ matches anything without binding; *rest matches the rest of an array.

Nested patterns

Patterns can be nested as deeply as the data:

ruby · try it yourself
response = {
  status: 200,
  body: {user: {name: "Lena", roles: ["admin", "editor"]}},
}

case response
in {status: 200, body: {user: {name: String => name, roles: [*, "admin", *]}}}
  puts "#{name} is an admin"
in {status: 200, body: {user: {name:}}}
  puts "#{name} is a regular user"
in {status: 400..499 => code}
  puts "client error #{code}"
end
Lena is an admin

[*, "admin", *] is a find pattern: it matches an array that contains "admin" anywhere.

Pinning with ^

A bare name in a pattern always creates a new variable. To compare against an existing variable's value, pin it with ^:

ruby · try it yourself
expected_id = 7

[{id: 7, ok: true}, {id: 9, ok: true}].each do |msg|
  case msg
  in {id: ^expected_id} then puts "reply to our request"
  in {id:} then puts "ignoring message #{id}"
  end
end
reply to our request
ignoring message 9

One-line patterns: => and in

ruby · try it yourself
config = {db: {host: "db.local", port: 5432}, debug: false}

config => {db: {host:, port:}}    # destructure (raises if no match)
puts "#{host}:#{port}"

p(config in {debug: true})        # boolean test
p(config in {db: {port: Integer}})
/app/output.s: --> /app/output.s

unexpected 'in'; expected a `)` to close the arguments
unexpected ')', expecting end-of-input
unexpected ')', ignoring it

> 1  config = {db: {host: "db.local", port: 5432}, debug: false}
> 3  config => {db: {host:, port:}}    # destructure (raises if no match)
> 4  puts "#{host}:#{port}"
> 6  p(config in {debug: true})        # boolean test
> 7  p(config in {db: {port: Integer}})
/app/output.s:6: syntax errors found (SyntaxError)
  4 | puts "#{host}:#{port}"
  5 |
> 6 | p(config in {debug: true})        # boolean test
    |          ^~ unexpected 'in'; expected a `)` to close the arguments
    |                          ^ unexpected ')', ignoring it
    |                          ^ unexpected ')', expecting end-of-input
> 7 | p(config in {db: {port: Integer}})
    |          ^~ unexpected 'in'; expected a `)` to close the arguments
    |                                  ^ unexpected ')', ignoring it
    |                                  ^ unexpected ')', expecting end-of-input

Matching your own objects

Struct and Data support patterns out of the box. Any class can by defining deconstruct (array patterns) and deconstruct_keys (hash patterns):

ruby · try it yourself
class Temperature
  attr_reader :degrees, :unit

  def initialize(degrees, unit) = (@degrees, @unit = degrees, unit)

  def deconstruct_keys(_keys) = {degrees:, unit:}
end

def feel(t)
  case t
  in {unit: :c, degrees: ..0} then "freezing"
  in {unit: :c, degrees: 1..20} then "cool"
  in {unit: :c} then "warm"
  in {unit: :f, degrees:} then feel(Temperature.new(((degrees - 32) * 5 / 9.0).round, :c))
  end
end

puts feel(Temperature.new(-3, :c))
puts feel(Temperature.new(15, :c))
puts feel(Temperature.new(86, :f))
freezing
cool
warm

Pattern cheat sheet

Pattern Matches
42, "a", :ok, nil that exact value (via ===)
Integer, 1..9, /re/ anything that === accepts
x anything, bound to x
_ anything, not bound
[a, b] / [a, *rest] arrays of that shape
[*, x, *] array containing a match for x
{k: pattern} / {k:} hashes with key k
p1 | p2 either pattern
pattern => name match and bind the whole value
^var the current value of var
pattern if cond pattern plus a guard

Test yourself

What does in {name:} do?

  1. Matches only hashes with exactly one key
  2. Matches a hash with a :name key and binds its value to name
  3. Assigns name to the hash
  4. Matches a string key "name"

What happens when no in branch matches and there is no else?

  1. It returns nil
  2. NoMatchingPatternError is raised
  3. The first branch runs
  4. Nothing

Why write in {id: ^wanted}?

  1. To bind id to a new variable
  2. To compare id with the existing variable wanted
  3. To negate the pattern
  4. To raise an error