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
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:
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:
begin
case {status: "weird"}
in {status: "ok"} then puts "fine"
end
rescue NoMatchingPatternError => e
puts "#{e.class}: #{e.message}"
endNoMatchingPatternError: {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":
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 => nchecks the type and binds the value ton.if ...after a pattern is a guard: an extra condition._matches anything without binding;*restmatches the rest of an array.
Nested patterns
Patterns can be nested as deeply as the data:
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}"
endLena 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 ^:
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
endreply to our request
ignoring message 9
One-line patterns: => and in
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):
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?
- Matches only hashes with exactly one key
- Matches a hash with a
:namekey and binds its value toname - Assigns name to the hash
- Matches a string key "name"
What happens when no in branch matches and there is no else?
- It returns nil
- NoMatchingPatternError is raised
- The first branch runs
- Nothing
Why write in {id: ^wanted}?
- To bind id to a new variable
- To compare id with the existing variable
wanted - To negate the pattern
- To raise an error