2019-12-25 13:39:42 -05:00
= Pattern matching
2020-11-01 00:28:24 -04:00
Pattern matching is a feature allowing deep matching of structured values: checking the structure and binding the matched parts to local variables.
2019-12-25 13:39:42 -05:00
2020-11-01 00:28:24 -04:00
Pattern matching in Ruby is implemented with the +case+/+in+ expression:
2019-12-25 13:39:42 -05:00
case <expression>
in <pattern1>
...
in <pattern2>
...
in <pattern3>
...
else
...
end
2020-12-21 12:08:32 -05:00
(Note that +in+ and +when+ branches can NOT be mixed in one +case+ expression.)
2020-12-12 21:50:14 -05:00
2020-12-24 05:35:03 -05:00
Or with the <code>=></code> operator and the +in+ operator, which can be used in a standalone expression:
2020-11-01 00:28:24 -04:00
<expression> => <pattern>
2019-12-25 13:39:42 -05:00
2020-12-12 21:50:14 -05:00
<expression> in <pattern>
2019-12-25 13:39:42 -05:00
2020-12-24 05:35:03 -05:00
The +case+/+in+ expression is _exhaustive_: if the value of the expression does not match any branch of the +case+ expression (and the +else+ branch is absent), +NoMatchingPatternError+ is raised.
2020-11-01 00:28:24 -04:00
2020-12-24 05:35:03 -05:00
Therefore, the +case+ expression might be used for conditional matching and unpacking:
2019-12-25 13:39:42 -05:00
2020-03-08 10:30:40 -04:00
config = {db: {user: 'admin', password: 'abc123'}}
2019-12-25 13:39:42 -05:00
case config
2020-03-08 10:30:40 -04:00
in db: {user:} # matches subhash and puts matched value in variable user
puts "Connect with user '#{user}'"
in connection: {username: }
puts "Connect with user '#{username}'"
else
puts "Unrecognized structure of config"
end
2020-04-04 23:15:18 -04:00
# Prints: "Connect with user 'admin'"
2019-12-25 13:39:42 -05:00
2020-12-24 05:35:03 -05:00
whilst the <code>=></code> operator is most useful when the expected data structure is known beforehand, to just unpack parts of it:
2019-12-25 13:39:42 -05:00
2020-03-08 10:30:40 -04:00
config = {db: {user: 'admin', password: 'abc123'}}
2019-12-25 13:39:42 -05:00
2020-11-01 00:28:24 -04:00
config => {db: {user:}} # will raise if the config's structure is unexpected
2019-12-25 13:39:42 -05:00
2020-03-08 10:30:40 -04:00
puts "Connect with user '#{user}'"
2020-04-04 23:15:18 -04:00
# Prints: "Connect with user 'admin'"
2019-12-25 13:39:42 -05:00
2020-12-21 12:08:32 -05:00
<code><expression> in <pattern></code> is the same as <code>case <expression>; in <pattern>; true; else false; end</code>.
2020-12-12 21:50:14 -05:00
You can use it when you only want to know if a pattern has been matched or not:
users = [{name: "Alice", age: 12}, {name: "Bob", age: 23}]
2020-12-24 05:35:03 -05:00
users.any? {|user| user in {name: /B/, age: 20..} } #=> true
2020-12-12 21:50:14 -05:00
2019-12-25 13:39:42 -05:00
See below for more examples and explanations of the syntax.
== Patterns
Patterns can be:
2020-12-24 05:35:03 -05:00
* any Ruby object (matched by the <code>===</code> operator, like in +when+); (<em>Value pattern</em>)
2020-12-19 23:28:40 -05:00
* array pattern: <code>[<subpattern>, <subpattern>, <subpattern>, ...]</code>; (<em>Array pattern</em>)
* find pattern: <code>[*variable, <subpattern>, <subpattern>, <subpattern>, ..., *variable]</code>; (<em>Find pattern</em>)
* hash pattern: <code>{key: <subpattern>, key: <subpattern>, ...}</code>; (<em>Hash pattern</em>)
* combination of patterns with <code>|</code>; (<em>Alternative pattern</em>)
2020-12-21 12:08:32 -05:00
* variable capture: <code><pattern> => variable</code> or <code>variable</code>; (<em>As pattern</em>, <em>Variable pattern</em>)
2019-12-25 13:39:42 -05:00
2020-12-19 23:22:53 -05:00
Any pattern can be nested inside array/find/hash patterns where <code><subpattern></code> is specified.
2019-12-25 13:39:42 -05:00
2020-12-19 23:22:53 -05:00
Array patterns and find patterns match arrays, or objects that respond to +deconstruct+ (see below about the latter).
2020-12-21 12:08:32 -05:00
Hash patterns match hashes, or objects that respond to +deconstruct_keys+ (see below about the latter). Note that only symbol keys are supported for hash patterns.
2019-12-25 13:39:42 -05:00
2020-12-24 05:35:03 -05:00
An important difference between array and hash pattern behavior is that arrays match only a _whole_ array:
2019-12-25 13:39:42 -05:00
case [1, 2, 3]
in [Integer, Integer]
"matched"
else
"not matched"
end
#=> "not matched"
2020-12-24 05:35:03 -05:00
while the hash matches even if there are other keys besides the specified part:
2019-12-25 13:39:42 -05:00
case {a: 1, b: 2, c: 3}
in {a: Integer}
"matched"
else
"not matched"
end
#=> "matched"
2020-12-24 05:35:03 -05:00
<code>{}</code> is the only exclusion from this rule. It matches only if an empty hash is given:
2020-12-21 12:08:32 -05:00
case {a: 1, b: 2, c: 3}
in {}
"matched"
else
"not matched"
end
#=> "not matched"
case {}
in {}
"matched"
else
"not matched"
end
#=> "matched"
2020-12-24 05:35:03 -05:00
There is also a way to specify there should be no other keys in the matched hash except those explicitly specified by the pattern, with <code>**nil</code>:
2019-12-25 13:39:42 -05:00
case {a: 1, b: 2}
in {a: Integer, **nil} # this will not match the pattern having keys other than a:
"matched a part"
in {a: Integer, b: Integer, **nil}
"matched a whole"
else
"not matched"
end
#=> "matched a whole"
Both array and hash patterns support "rest" specification:
case [1, 2, 3]
in [Integer, *]
"matched"
else
"not matched"
end
#=> "matched"
case {a: 1, b: 2, c: 3}
in {a: Integer, **}
"matched"
else
"not matched"
end
#=> "matched"
2020-12-24 05:35:03 -05:00
In +case+ (but not in <code>=></code> and +in+) expressions, parentheses around both kinds of patterns could be omitted:
2019-12-25 13:39:42 -05:00
case [1, 2]
in Integer, Integer
"matched"
else
"not matched"
end
#=> "matched"
case {a: 1, b: 2, c: 3}
in a: Integer
"matched"
else
"not matched"
end
#=> "matched"
2020-12-21 12:08:32 -05:00
Find pattern is similar to array pattern but it can be used to check if the given object has any elements that match the pattern:
2020-12-19 23:22:53 -05:00
case ["a", 1, "b", "c", 2]
in [*, String, String, *]
"matched"
else
"not matched"
end
2019-12-25 13:39:42 -05:00
== Variable binding
2020-12-24 05:35:03 -05:00
Besides deep structural checks, one of the very important features of the pattern matching is the binding of the matched parts to local variables. The basic form of binding is just specifying <code>=> variable_name</code> after the matched (sub)pattern (one might find this similar to storing exceptions in local variables in a <code>rescue ExceptionClass => var</code> clause):
2019-12-25 13:39:42 -05:00
case [1, 2]
in Integer => a, Integer
"matched: #{a}"
else
"not matched"
end
#=> "matched: 1"
case {a: 1, b: 2, c: 3}
in a: Integer => m
"matched: #{m}"
else
"not matched"
end
#=> "matched: 1"
2020-12-24 05:35:03 -05:00
If no additional check is required, for only binding some part of the data to a variable, a simpler form could be used:
2019-12-25 13:39:42 -05:00
case [1, 2]
in a, Integer
"matched: #{a}"
else
"not matched"
end
#=> "matched: 1"
case {a: 1, b: 2, c: 3}
in a: m
"matched: #{m}"
else
"not matched"
end
#=> "matched: 1"
2020-12-21 12:08:32 -05:00
For hash patterns, even a simpler form exists: key-only specification (without any sub-pattern) binds the local variable with the key's name, too:
2019-12-25 13:39:42 -05:00
case {a: 1, b: 2, c: 3}
in a:
"matched: #{a}"
else
"not matched"
end
#=> "matched: 1"
Binding works for nested patterns as well:
case {name: 'John', friends: [{name: 'Jane'}, {name: 'Rajesh'}]}
in name:, friends: [{name: first_friend}, *]
"matched: #{first_friend}"
else
"not matched"
end
#=> "matched: Jane"
The "rest" part of a pattern also can be bound to a variable:
case [1, 2, 3]
in a, *rest
"matched: #{a}, #{rest}"
else
"not matched"
end
#=> "matched: 1, [2, 3]"
case {a: 1, b: 2, c: 3}
in a:, **rest
"matched: #{a}, #{rest}"
else
"not matched"
end
#=> "matched: 1, {:b=>2, :c=>3}"
Binding to variables currently does NOT work for alternative patterns joined with <code>|</code>:
case {a: 1, b: 2}
in {a: } | Array
"matched: #{a}"
else
"not matched"
end
# SyntaxError (illegal variable in alternative pattern (a))
2020-12-21 12:08:32 -05:00
Variables that start with <code>_</code> are the only exclusions from this rule:
2019-12-25 13:39:42 -05:00
case {a: 1, b: 2}
2020-12-21 12:08:32 -05:00
in {a: _, b: _foo} | Array
"matched: #{_}, #{_foo}"
2019-12-25 13:39:42 -05:00
else
"not matched"
end
2020-12-22 12:32:30 -05:00
# => "matched: 1, 2"
2019-12-25 13:39:42 -05:00
2020-12-24 05:35:03 -05:00
It is, though, not advised to reuse the bound value, as this pattern's goal is to signify a discarded value.
2019-12-25 13:39:42 -05:00
== Variable pinning
2020-12-24 05:35:03 -05:00
Due to the variable binding feature, existing local variable can not be straightforwardly used as a sub-pattern:
2019-12-25 13:39:42 -05:00
expectation = 18
case [1, 2]
in expectation, *rest
"matched. expectation was: #{expectation}"
else
"not matched. expectation was: #{expectation}"
end
# expected: "not matched. expectation was: 18"
# real: "matched. expectation was: 1" -- local variable just rewritten
2020-12-24 05:35:03 -05:00
For this case, the pin operator <code>^</code> can be used, to tell Ruby "just use this value as part of the pattern":
2019-12-25 13:39:42 -05:00
expectation = 18
case [1, 2]
in ^expectation, *rest
"matched. expectation was: #{expectation}"
else
"not matched. expectation was: #{expectation}"
end
#=> "not matched. expectation was: 18"
2020-12-24 05:35:03 -05:00
One important usage of variable pinning is specifying that the same value should occur in the pattern several times:
2019-12-25 13:39:42 -05:00
jane = {school: 'high', schools: [{id: 1, level: 'middle'}, {id: 2, level: 'high'}]}
john = {school: 'high', schools: [{id: 1, level: 'middle'}]}
case jane
in school:, schools: [*, {id:, level: ^school}] # select the last school, level should match
"matched. school: #{id}"
else
"not matched"
end
#=> "matched. school: 2"
case john # the specified school level is "high", but last school does not match
in school:, schools: [*, {id:, level: ^school}]
"matched. school: #{id}"
else
"not matched"
end
#=> "not matched"
2020-12-21 12:08:32 -05:00
== Matching non-primitive objects: +deconstruct+ and +deconstruct_keys+
2019-12-25 13:39:42 -05:00
2020-12-24 05:35:03 -05:00
As already mentioned above, array, find, and hash patterns besides literal arrays and hashes will try to match any object implementing +deconstruct+ (for array/find patterns) or +deconstruct_keys+ (for hash patterns).
2019-12-25 13:39:42 -05:00
class Point
def initialize(x, y)
@x, @y = x, y
end
def deconstruct
puts "deconstruct called"
[@x, @y]
end
def deconstruct_keys(keys)
puts "deconstruct_keys called with #{keys.inspect}"
{x: @x, y: @y}
end
end
case Point.new(1, -2)
2020-12-21 12:08:32 -05:00
in px, Integer # sub-patterns and variable binding works
2019-12-25 13:39:42 -05:00
"matched: #{px}"
else
"not matched"
end
# prints "deconstruct called"
"matched: 1"
case Point.new(1, -2)
in x: 0.. => px
"matched: #{px}"
else
"not matched"
end
# prints: deconstruct_keys called with [:x]
#=> "matched: 1"
+keys+ are passed to +deconstruct_keys+ to provide a room for optimization in the matched class: if calculating a full hash representation is expensive, one may calculate only the necessary subhash. When the <code>**rest</code> pattern is used, +nil+ is passed as a +keys+ value:
case Point.new(1, -2)
in x: 0.. => px, **rest
"matched: #{px}"
else
"not matched"
end
# prints: deconstruct_keys called with nil
#=> "matched: 1"
2020-12-24 05:35:03 -05:00
Additionally, when matching custom classes, the expected class can be specified as part of the pattern and is checked with <code>===</code>
2019-12-25 13:39:42 -05:00
class SuperPoint < Point
end
case Point.new(1, -2)
in SuperPoint(x: 0.. => px)
"matched: #{px}"
else
"not matched"
end
#=> "not matched"
case SuperPoint.new(1, -2)
in SuperPoint[x: 0.. => px] # [] or () parentheses are allowed
"matched: #{px}"
else
"not matched"
end
#=> "matched: 1"
== Guard clauses
+if+ can be used to attach an additional condition (guard clause) when the pattern matches. This condition may use bound variables:
case [1, 2]
in a, b if b == a*2
"matched"
else
"not matched"
end
#=> "matched"
case [1, 1]
in a, b if b == a*2
"matched"
else
"not matched"
end
#=> "not matched"
+unless+ works, too:
case [1, 1]
in a, b unless b == a*2
"matched"
else
"not matched"
end
#=> "matched"
== Current feature status
2020-12-24 05:35:03 -05:00
As of Ruby 3.0, one-line pattern matching and find patterns are considered _experimental_: its syntax can change in the future. Every time you use these features in code, a warning will be printed:
2019-12-25 13:39:42 -05:00
2020-11-01 00:28:24 -04:00
[0] => [*, 0, *]
# warning: Find pattern is experimental, and the behavior may change in future versions of Ruby!
# warning: One-line pattern matching is experimental, and the behavior may change in future versions of Ruby!
2019-12-25 13:39:42 -05:00
2020-12-24 05:35:03 -05:00
To suppress this warning, one may use the Warning::[]= method:
2019-12-25 13:39:42 -05:00
Warning[:experimental] = false
2020-11-01 00:28:24 -04:00
eval('[0] => [*, 0, *]')
2019-12-25 13:39:42 -05:00
# ...no warning printed...
2020-12-24 05:35:03 -05:00
Note that pattern-matching warnings are raised at compile time, so this will not suppress the warning:
2019-12-25 13:39:42 -05:00
Warning[:experimental] = false # At the time this line is evaluated, the parsing happened and warning emitted
2020-11-01 00:28:24 -04:00
[0] => [*, 0, *]
2019-12-25 13:39:42 -05:00
So, only subsequently loaded files or `eval`-ed code is affected by switching the flag.
2020-12-24 05:35:03 -05:00
Alternatively, the command line option <code>-W:no-experimental</code> can be used to turn off "experimental" feature warnings.
2020-12-19 23:22:53 -05:00
== Appendix A. Pattern syntax
2020-12-21 12:08:32 -05:00
2020-12-19 23:22:53 -05:00
Approximate syntax is:
pattern: value_pattern
| variable_pattern
| alternative_pattern
| as_pattern
| array_pattern
| find_pattern
| hash_pattern
value_pattern: literal
| Constant
| ^variable
2021-03-21 02:12:54 -04:00
| ^(expression)
2020-12-19 23:22:53 -05:00
variable_pattern: variable
alternative_pattern: pattern | pattern | ...
as_pattern: pattern => variable
array_pattern: [pattern, ..., *variable]
| Constant(pattern, ..., *variable)
| Constant[pattern, ..., *variable]
find_pattern: [*variable, pattern, ..., *variable]
2020-12-19 23:28:40 -05:00
| Constant(*variable, pattern, ..., *variable)
| Constant[*variable, pattern, ..., *variable]
2020-12-19 23:22:53 -05:00
2020-12-19 23:25:43 -05:00
hash_pattern: {key: pattern, key:, ..., **variable}
| Constant(key: pattern, key:, ..., **variable)
| Constant[key: pattern, key:, ..., **variable]
2020-12-19 23:22:53 -05:00
== Appendix B. Some undefined behavior examples
To leave room for optimization in the future, the specification contains some undefined behavior.
Use of a variable in an unmatched pattern:
case [0, 1]
in [a, 2]
"not matched"
in b
"matched"
in c
"not matched"
end
a #=> undefined
c #=> undefined
Number of +deconstruct+, +deconstruct_keys+ method calls:
$i = 0
ary = [0]
def ary.deconstruct
$i += 1
self
end
case ary
in [0, 1]
"not matched"
in [0]
"matched"
end
$i #=> undefined