Ruby 2.7 — Pattern Matching — First Impressions

Brandon Weaver
Apr 17 · 5 min read

The Short Version

Literal Matches

case 0
in 0 then true
else false
end
# => true

Multiple Matchers

case 0
in 0 | 1
true
end
# => true
case 0
in a | 0
end
# Error: illegal variable in alternative pattern

Captured Variables

case true
in a
a
end
# => true
case 0
in a if a == 0
true
end
# => true
case 0
in 0 => a
a == 0
end
case 0
in _ | _a
true
end

Destructuring

case [0, 1]
in a, a
a == 1
end
# => true
class C
class << self
attr_accessor :keys
end
def initialize(obj)
@obj = obj
end
def deconstruct
@obj
end
def deconstruct_keys(keys)
C.keys = keys
@obj
end
end
[[0, 1], C.new([0, 1])].all? do |i|
case i
in 0, 1
true
end
end
[[0], C.new([0])].all? do |i|
case i
in 0, 1
else
true
end
end
case []
in *a
a == []
end
case [0, 1, 2]
in *a, 1, 2
a == [0]
end
case 0
in *
true
end
case {a: 0}
in a: 0
true
end
case {}
in **a
a == {}
end

Triple Equals

case 'abc'
in /a/
true
end
case 0
in -> i { i == 0 }
true
end
case [0, 1, 2, 3, 4, 5]
in [0..1, 0...2, 0.., 0..., (...5), (..5)]
true
end
case object
in method_a: 0..10, method_b: String
true
end

Pin Operator

a = /a/
case 'abc'
in ^a
true
end
case [0, 0]
in a, ^a
a == 0
end

Thoughts?

Brandon Weaver

Written by

Ruby and Javascript at Square. Typically responds in puns. Opinions are my own.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade