Pattern matching
suggest changePattern matching (case/in) checks the shape of a value and pulls parts of it into local variables in one step. A case/when statement (see Case statement) only compares a value with ===. A case/in pattern can also look inside arrays, hashes and your own objects, bind what it finds to variables, and add guard conditions.
Pattern matching was added in Ruby 2.7 and has been stable since Ruby 3.0. The examples were run with Ruby 4.0.
A first example
def describe(value)
case value
in Integer | Float => n if n.negative? then "negative number #{n}"
in 0 then "zero"
in Integer then "integer"
in Float then "float"
in "" then "empty string"
in String => s then "string of length #{s.size}"
in [] then "empty array"
in [x] then "one-element array with #{x.inspect}"
in {name: String => name} then "something named #{name}"
in nil then "nil"
else "something else: #{value.class}"
end
end
[-3, 0, 42, 3.14, "", "hello", [], [:a], {name: "Ruby", age: 30}, nil, :sym].each do |v|
puts "#{v.inspect.ljust(25)} => #{describe(v)}"
end
-3 => negative number -3
0 => zero
42 => integer
3.14 => float
"" => empty string
"hello" => string of length 5
[] => empty array
[:a] => one-element array with :a
{name: "Ruby", age: 30} => something named Ruby
nil => nil
:sym => something else: Symbol
The in clauses are tried from top to bottom and the first match wins. Every kind of pattern shows up here:
- Value patterns (
0,"",Integer,nil) compare with===. - Alternative patterns (
Integer | Float) match if any of the alternatives matches. - Binding (
=> n) stores the matched value in a variable. - Guards (
if n.negative?) add a condition that must also be true. - Array patterns (
[],[x]) and hash patterns ({name: ...}) look inside the value.
Value patterns
Any expression that isn't a pattern is compared with pattern === value, as in case/when. So classes, ranges, regular expressions and lambdas all work:
def classify(x)
case x
in 1..9 then "single digit"
in 10.. then "big"
in /\A\d{3}-\d{4}\z/ then "phone number"
in :ok | :done then "finished"
in Symbol then "other symbol"
in ->(v) { v.respond_to?(:each) } then "enumerable-ish"
else "unknown"
end
end
[5, 100, "555-1234", :ok, :done, :pending, {a: 1}, "nope"].each do |v|
puts "#{v.inspect.ljust(12)} #{classify(v)}"
end
5 single digit
100 big
"555-1234" phone number
:ok finished
:done finished
:pending other symbol
{a: 1} enumerable-ish
"nope" unknown
Array patterns
An array pattern matches an array with exactly that many elements, and each element must match its sub-pattern. A bare name like x matches anything and binds it. *rest matches any number of elements, and a bare * does the same without binding them:
def shape(arr)
case arr
in [] then "empty"
in [x] then "one: #{x}"
in [x, y] then "two: #{x}, #{y}"
in [first, *rest] then "first=#{first}, rest=#{rest}"
end
end
p shape([])
p shape([1])
p shape([1, 2])
p shape([1, 2, 3, 4])
case [1, [2, 3], 4]
in [Integer => a, [b, *], *]
puts "a=#{a} b=#{b}"
end
case [1, 2, 3, 4, 5]
in [first, *, last]
puts "first=#{first} last=#{last}"
end
case [:point, 3, 4]
in [:point, _, _] => whole
p whole
end
"empty"
"one: 1"
"two: 1, 2"
"first=1, rest=[2, 3, 4]"
a=1 b=2
first=1 last=5
[:point, 3, 4]
_ is a wildcard: it matches anything and you don't care about the value. You can use _ several times in one pattern. => whole binds the whole matched value, and it works on any pattern, not only at the top level.
Patterns can be nested as deep as you like. An array pattern matches only objects that respond to deconstruct. Array and Struct do, but Hash and String don't.
Find pattern
A find pattern, [*pre, pattern, *post], searches for a sub-pattern anywhere in the array. It has a splat on both ends:
events = [
[:login, "alice"],
[:click, "button", 3],
[:error, 500, "boom"],
[:click, "link", 1],
]
events.each do |event|
case event
in [*, :error, *post]
puts "error event, rest: #{post.inspect}"
in [*, String => target, Integer => n, *]
puts "#{target} clicked #{n} times"
in [:login, user]
puts "#{user} logged in"
end
end
case [1, 42, "x", 99, :y]
in [*pre, String => s, *post]
puts "pre=#{pre} s=#{s} post=#{post}"
end
alice logged in
button clicked 3 times
error event, rest: [500, "boom"]
link clicked 1 times
pre=[1, 42] s=x post=[99, :y]
[:login, "alice"] doesn't match the second pattern even though it has a string, because there is no integer after it. The search stops at the first position where the middle patterns match.
Hash patterns
Hash patterns match by key. key: with no value matches any value and binds it to a local variable with the same name. key: pattern checks the value against a sub-pattern:
config = {db: {user: "admin", pass: "secret", port: 5432}, mode: "dev", debug: true}
case config
in {db: {user:, port: Integer => port}, mode: "dev" | "test" => mode}
puts "user=#{user} port=#{port} mode=#{mode}"
end
# Extra keys are ignored by default
case {status: 200, body: "ok", headers: {}}
in {status: 200 | 201 => code}
puts "success #{code}"
end
# **rest collects the remaining keys
case {name: "Ann", age: 31, role: :admin, team: "core"}
in {name: String => name, **rest}
puts "name=#{name} rest=#{rest}"
end
# **nil means "no other keys allowed"
[{x: 1, y: 2}, {x: 1, y: 2, z: 3}].each do |h|
case h
in {x:, y:, **nil} then puts "exact 2D point #{x},#{y}"
in {x:, y:} then puts "point with extra keys: #{h.keys}"
end
end
# braces can be omitted at the top level
case {type: :circle, r: 2}
in type: :circle, r:
puts "circle area #{(3.14159 * r * r).round(2)}"
end
# an empty hash pattern only matches an empty hash
p(({} in {}))
p(({a: 1} in {}))
user=admin port=5432 mode=dev
success 200
name=Ann rest={age: 31, role: :admin, team: "core"}
exact 2D point 1,2
point with extra keys: [:x, :y, :z]
circle area 12.57
true
false
Unlike array patterns, hash patterns ignore extra keys. That way you can match a large hash (a JSON response, an options hash) by looking only at the keys you care about. Use **nil when you need an exact set of keys.
Keys must be symbols
Hash pattern keys are always symbols. {"name" => n} is a syntax error in a pattern, and {"name": n} is just another way to write the symbol :name. Hashes from JSON.parse have string keys by default, so parse with symbolize_names: true before you match them (see JSON with Ruby):
require 'json'
json = '{"user": {"name": "Ann", "roles": ["admin", "dev"]}}'
data = JSON.parse(json)
p data
p((data in {user: {name: String}})) # string keys: no match
data = JSON.parse(json, symbolize_names: true)
case data
in {user: {name: String => name, roles: [*, "admin", *]}}
puts "#{name} is an admin"
end
{"user" => {"name" => "Ann", "roles" => ["admin", "dev"]}}
false
Ann is an admin
Guards
A guard is an if or unless after the pattern. It runs only if the pattern matched, and it can use the variables the pattern bound:
def check_point(pt)
case pt
in {x: 0, y: 0} then "origin"
in {x:, y:} if x == y then "on the diagonal at #{x}"
in {x:, y:} unless x.positive? then "left half"
in {x:, y:} then "at (#{x}, #{y})"
end
end
p check_point({x: 0, y: 0})
p check_point({x: 5, y: 5})
p check_point({x: -2, y: 7})
p check_point({x: 3, y: 1})
"origin"
"on the diagonal at 5"
"left half"
"at (3, 1)"
The pin operator ^
A bare name in a pattern always binds a new value. It never compares with an existing variable. To match against the current value of a variable, pin it with ^:
expected = 200
[200, 404].each do |status|
case status
in ^expected then puts "#{status}: as expected"
in Integer then puts "#{status}: unexpected"
end
end
# without ^ the pattern just rebinds the variable
case 404
in expected
puts "matched anything, expected is now #{expected}"
end
# pin a previously bound variable from the same pattern
[[1, 1], [1, 2]].each do |pair|
case pair
in [a, ^a] then puts "#{pair}: both equal"
in [a, b] then puts "#{pair}: different"
end
end
# pin an expression with ^( )
limit = 10
case {count: 20}
in {count: ^(limit * 2)} then puts "exactly twice the limit"
end
# pin instance, class and global variables
class Checker
def initialize(v) = @v = v
def check(x) = (x in ^@v)
end
p Checker.new(5).check(5)
p Checker.new(5).check(6)
200: as expected
404: unexpected
matched anything, expected is now 404
[1, 1]: both equal
[1, 2]: different
exactly twice the limit
true
false
Forgetting the ^ is the most common pattern matching bug. in expected matches every value and silently overwrites expected.
Constants (in MAX_SIZE) and method calls are compared with ===, so they don't need a pin. Only local, instance, class and global variables and arbitrary expressions do.
When nothing matches
A case/in without an else raises NoMatchingPatternError when no clause matches. case/when would just return nil. This is deliberate: an unexpected shape is a bug, and it's better to find out right away. When the failure is a missing hash key, the error is the subclass NoMatchingPatternKeyError, which tells you which key was missing:
begin
case 3.5
in Integer then puts "int"
in String then puts "str"
end
rescue NoMatchingPatternError => e
puts "#{e.class}: #{e.message}"
end
begin
{name: "Ann"} => {name:, email:}
rescue NoMatchingPatternKeyError => e
puts "#{e.class}: #{e.message}"
p e.key
p e.matchee
p e.class.superclass
end
NoMatchingPatternError: 3.5
NoMatchingPatternKeyError: {name: "Ann"}: key not found: :email
:email
{name: "Ann"}
NoMatchingPatternError
Add an else branch when not matching is a normal outcome.
Standalone patterns: => and in
You can use a pattern without case:
expr => pattern(rightward assignment) destructures the value and raisesNoMatchingPatternErrorif it doesn't match.expr in patternreturnstrueorfalseand never raises. Variables are still bound when it matches.
# rightward assignment: destructure or raise
response = {status: 200, body: {id: 7, tags: ["a", "b"]}}
response => {status:, body: {id:, tags: [first_tag, *]}}
puts "status=#{status} id=#{id} first_tag=#{first_tag}"
# a plain variable pattern is just assignment
42 => answer
p answer
# `in` returns true/false and never raises
p((1 in Integer))
p(("x" in Integer))
if response in {status: 200..299, body: {id: Integer => new_id}}
puts "created #{new_id}"
end
values = [1, "two", :three, 4.0, nil]
p values.select { it in Integer | Float }
p values.reject { it in nil }
status=200 id=7 first_tag=a
42
true
false
created 7
[1, 4.0]
[1, "two", :three, 4.0]
expr => {a:, b:} is a handy way to pull several keys out of a nested hash and check that they exist, all in one line. When you pass an in expression straight to a method, wrap it in an extra pair of parentheses: p((x in Integer)). Ruby can't parse p(x in Integer).
Matching your own objects
Array patterns call deconstruct on the value and hash patterns call deconstruct_keys(keys). To make a class matchable, define these methods. Write Const(...) or Const[...] to check the class first (with Const === value) and then match the contents:
class Point
attr_reader :x, :y
def initialize(x, y)
@x, @y = x, y
end
# used by array patterns: Point[x, y] or Point(x, y)
def deconstruct
puts " deconstruct called"
[x, y]
end
# used by hash patterns: Point(x:, y:)
def deconstruct_keys(keys)
puts " deconstruct_keys called with #{keys.inspect}"
{x: x, y: y}
end
end
def where(pt)
case pt
in Point[0, 0] then "origin"
in Point(x:, y: 0) then "on x axis at #{x}"
in Point(x: 0, **rest) then "on y axis, rest=#{rest}"
in Point[x, y] then "at #{x},#{y}"
end
end
puts where(Point.new(0, 0))
puts where(Point.new(4, 0))
puts where(Point.new(0, 9))
puts where(Point.new(2, 3))
deconstruct called
origin
deconstruct called
deconstruct_keys called with [:x, :y]
on x axis at 4
deconstruct called
deconstruct_keys called with [:x, :y]
deconstruct_keys called with nil
on y axis, rest={y: 9}
deconstruct called
deconstruct_keys called with [:x, :y]
deconstruct_keys called with nil
at 2,3
The trace shows two things:
deconstruct_keysreceives the list of keys the pattern mentions, ornilwhen the pattern has**rest(then every key is needed). If computing the values is expensive, return only the requested keys.- Within one
case, the result ofdeconstructis cached. The last clause reused the array from the first clause instead of callingdeconstructagain.
Here's a version that computes only the requested keys:
class User
attr_reader :id, :name, :email
def initialize(id, name, email)
@id, @name, @email = id, name, email
end
def deconstruct_keys(keys)
all = {id:, name:, email:}
keys ? all.slice(*keys) : all
end
end
u = User.new(1, "Ann", "ann@example.com")
case u
in {email: /@example\.com\z/ => email}
puts "internal user: #{email}"
end
u => {name:}
p name
internal user: ann@example.com
"Ann"
Struct and Data
Struct (see Struct) and Data already define both methods, so their instances work with array and hash patterns out of the box. This makes them a good fit for modelling values you'll later match on:
Point = Struct.new(:x, :y)
Circle = Data.define(:center, :radius)
Rect = Data.define(:top_left, :width, :height)
def area(shape)
case shape
in Circle[center: _, radius: r] then (Math::PI * r**2).round(2)
in Rect(width: w, height: h) then w * h
end
end
def describe(shape)
case shape
in Circle(center: Point[0, 0], radius:) then "circle at origin, r=#{radius}"
in Circle(center: Point[x, y]) then "circle at #{x},#{y}"
in Rect(width: s, height: ^s) then "square #{s}x#{s}"
in Rect then "rectangle"
end
end
shapes = [
Circle.new(center: Point.new(0, 0), radius: 1),
Circle.new(center: Point.new(2, 5), radius: 3),
Rect.new(top_left: Point.new(0, 0), width: 4, height: 4),
Rect.new(top_left: Point.new(1, 1), width: 2, height: 6),
]
shapes.each do |s|
puts "#{describe(s).ljust(24)} area=#{area(s)}"
end
p Point.new(1, 2).deconstruct
p Point.new(1, 2).deconstruct_keys([:x])
p Circle.new(center: nil, radius: 2).deconstruct_keys(nil)
circle at origin, r=1 area=3.14
circle at 2,5 area=28.27
square 4x4 area=16
rectangle area=12
[1, 2]
{x: 1}
{center: nil, radius: 2}
Rect(width: s, height: ^s) pins a variable bound earlier in the same pattern, so it matches only when width equals height.
Practical examples
Evaluating a small expression tree
Pattern matching works well for tree-shaped data such as syntax trees, where each node is a tagged array:
def evaluate(node, env = {})
case node
in Integer | Float then node
in Symbol => name
env.fetch(name) { raise NameError, "undefined variable #{name}" }
in [:+, left, right] then evaluate(left, env) + evaluate(right, env)
in [:-, left, right] then evaluate(left, env) - evaluate(right, env)
in [:*, left, right] then evaluate(left, env) * evaluate(right, env)
in [:/, _, 0] then raise ZeroDivisionError, "division by literal zero"
in [:/, left, right] then evaluate(left, env) / evaluate(right, env)
in [:let, Symbol => name, value, body]
evaluate(body, env.merge(name => evaluate(value, env)))
in [op, *] then raise ArgumentError, "unknown operator #{op.inspect}"
end
end
p evaluate([:+, 1, [:*, 2, 3]])
p evaluate([:let, :x, 10, [:-, :x, [:/, :x, 4]]])
p evaluate([:*, :rate, 100.0], {rate: 0.25})
[[:/, 5, 0], [:pow, 2, 8], [:+, :y, 1]].each do |bad|
evaluate(bad)
rescue => e
puts "#{bad.inspect}: #{e.class}: #{e.message}"
end
7
8
25.0
[:/, 5, 0]: ZeroDivisionError: division by literal zero
[:pow, 2, 8]: ArgumentError: unknown operator :pow
[:+, :y, 1]: NameError: undefined variable y
Dispatching commands
Splitting a line into words and matching the resulting array makes a compact command parser. Number of arguments, literal command names and the catch-all case are all handled in one place:
def handle(line)
case line.split
in ["help"] then "commands: get KEY, set KEY VALUE, del KEY..., quit"
in ["get", key] then "GET #{key}"
in ["set", key, value] then "SET #{key}=#{value}"
in ["set", *] then "usage: set KEY VALUE"
in ["del", _, *] => args then "DEL #{args.drop(1).join(', ')}"
in ["quit" | "exit"] then "bye"
in [] then ""
in [cmd, *] then "unknown command: #{cmd}"
end
end
["help", "get name", "set name Ann", "set name", "del a b c", "exit", "", "frob x"].each do |l|
puts "#{l.inspect.ljust(16)} -> #{handle(l).inspect}"
end
"help" -> "commands: get KEY, set KEY VALUE, del KEY..., quit"
"get name" -> "GET name"
"set name Ann" -> "SET name=Ann"
"set name" -> "usage: set KEY VALUE"
"del a b c" -> "DEL a, b, c"
"exit" -> "bye"
"" -> ""
"frob x" -> "unknown command: frob"
Gotchas
Alternatives can't bind variables. In [x, 1] | [1, x], which branch would set x? Ruby rejects it at parse time:
case [1, 2]
in [x, 1] | [1, x]
p x
end
> 2 | in [x, 1] | [1, x]
| ^ variable capture in alternative pattern
| ^ variable capture in alternative pattern
Names that start with an underscore (_x) are allowed in alternatives because they mean "ignore this value". To get the value, bind the whole alternative instead: in (Integer | Float) => n.
Variables from a failed clause can leak. Bindings are assigned while matching runs, so a clause that fails partway through can leave variables set:
case [1, 2]
in [a, 99] then puts "no"
in _ then p a
end
1
Don't rely on this. Use only the variables bound by the clause that actually matched.
Other things to keep in mind:
- A bare name always binds. Use
^nameto compare with an existing variable. - Hash patterns match only symbol keys. Convert string-keyed hashes first.
- Array patterns require an exact length unless they contain
*. Hash patterns allow extra keys unless they end with**nil. - Without
else, a non-matchingcase/inraisesNoMatchingPatternErrorinstead of returningnil. case/whenis still the better tool for simple===comparisons. Usecase/inwhen you need to destructure or bind.