Pattern matching¶↑
Pattern matching is a feature allowing deep matching of structured values: checking the structure and binding the matched parts to local variables.
Pattern matching in Ruby is implemented with thecase/in expression:
case <expression>in <pattern1> ...in <pattern2> ...in <pattern3> ...else ...end
(Note thatin andwhen branches can NOT be mixed in onecase expression.)
Or with the=> operator and thein operator, which can be used in a standalone expression:
<expression> => <pattern><expression> in <pattern>
Thecase/in expression isexhaustive: if the value of the expression does not match any branch of thecase expression (and theelse branch is absent),NoMatchingPatternError is raised.
Therefore, thecase expression might be used for conditional matching and unpacking:
config = {db: {user:'admin',password:'abc123'}}caseconfigindb: {user:}# matches subhash and puts matched value in variable userputs"Connect with user '#{user}'"inconnection: {username: }puts"Connect with user '#{username}'"elseputs"Unrecognized structure of config"end# Prints: "Connect with user 'admin'"
whilst the=> operator is most useful when the expected data structure is known beforehand, to just unpack parts of it:
config = {db: {user:'admin',password:'abc123'}}config=> {db: {user:}}# will raise if the config's structure is unexpectedputs"Connect with user '#{user}'"# Prints: "Connect with user 'admin'"
<expression> in <pattern> is the same ascase <expression>; in <pattern>; true; else false; end. 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}]users.any? {|user|userin {name:/B/,age:20..} }#=> true
See below for more examples and explanations of the syntax.
Patterns¶↑
Patterns can be:
any Ruby object (matched by the
===operator, like inwhen); (Value pattern)array pattern:
[<subpattern>, <subpattern>, <subpattern>, ...]; (Array pattern)find pattern:
[*variable, <subpattern>, <subpattern>, <subpattern>, ..., *variable]; (Find pattern)hash pattern:
{key: <subpattern>, key: <subpattern>, ...}; (Hash pattern)combination of patterns with
|; (Alternative pattern)variable capture:
<pattern> => variableorvariable; (As pattern,Variable pattern)
Any pattern can be nested inside array/find/hash patterns where<subpattern> is specified.
Array patterns and find patterns match arrays, or objects that respond todeconstruct (see below about the latter).Hash patterns match hashes, or objects that respond todeconstruct_keys (see below about the latter). Note that only symbol keys are supported for hash patterns.
An important difference between array and hash pattern behavior is that arrays match only awhole array:
case [1,2,3]in [Integer,Integer]"matched"else"not matched"end#=> "not matched"
while the hash matches even if there are other keys besides the specified part:
case {a:1,b:2,c:3}in {a:Integer}"matched"else"not matched"end#=> "matched"
{} is the only exclusion from this rule. It matches only if an empty hash is given:
case {a:1,b:2,c:3}in {}"matched"else"not matched"end#=> "not matched"case {}in {}"matched"else"not matched"end#=> "matched"
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**nil:
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"
Parentheses around both kinds of patterns could be omitted:
case [1,2]inInteger,Integer"matched"else"not matched"end#=> "matched"case {a:1,b:2,c:3}ina:Integer"matched"else"not matched"end#=> "matched"[1,2]=>a,b[1,2]ina,b{a:1,b:2,c:3}=>a:{a:1,b:2,c:3}ina:
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:
case ["a",1,"b","c",2]in [*,String,String,*]"matched"else"not matched"end
Variable binding¶↑
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=> variable_name after the matched (sub)pattern (one might find this similar to storing exceptions in local variables in arescue ExceptionClass => var clause):
case [1,2]inInteger=>a,Integer"matched: #{a}"else"not matched"end#=> "matched: 1"case {a:1,b:2,c:3}ina:Integer=>m"matched: #{m}"else"not matched"end#=> "matched: 1"
If no additional check is required, for only binding some part of the data to a variable, a simpler form could be used:
case [1,2]ina,Integer"matched: #{a}"else"not matched"end#=> "matched: 1"case {a:1,b:2,c:3}ina:m"matched: #{m}"else"not matched"end#=> "matched: 1"
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:
case {a:1,b:2,c:3}ina:"matched: #{a}"else"not matched"end#=> "matched: 1"
Binding works for nested patterns as well:
case {name:'John',friends: [{name:'Jane'}, {name:'Rajesh'}]}inname:,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]ina,*rest"matched: #{a}, #{rest}"else"not matched"end#=> "matched: 1, [2, 3]"case {a:1,b:2,c:3}ina:,**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|:
case {a: 1, b: 2}in {a: } | Array "matched: #{a}"else "not matched"end# SyntaxError (illegal variable in alternative pattern (a))Variables that start with_ are the only exclusions from this rule:
case {a:1,b:2}in {a:_,b:_foo}|Array"matched: #{_}, #{_foo}"else"not matched"end# => "matched: 1, 2"
It is, though, not advised to reuse the bound value, as this pattern’s goal is to signify a discarded value.
Variable pinning¶↑
Due to the variable binding feature, existing local variable can not be straightforwardly used as a sub-pattern:
expectation =18case [1,2]inexpectation,*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
For this case, the pin operator^ can be used, to tell Ruby “just use this value as part of the pattern”:
expectation =18case [1,2]in^expectation,*rest"matched. expectation was: #{expectation}"else"not matched. expectation was: #{expectation}"end#=> "not matched. expectation was: 18"
One important usage of variable pinning is specifying that the same value should occur in the pattern several times:
jane = {school:'high',schools: [{id:1,level:'middle'}, {id:2,level:'high'}]}john = {school:'high',schools: [{id:1,level:'middle'}]}casejaneinschool:,schools: [*, {id:,level:^school}]# select the last school, level should match"matched. school: #{id}"else"not matched"end#=> "matched. school: 2"casejohn# the specified school level is "high", but last school does not matchinschool:,schools: [*, {id:,level:^school}]"matched. school: #{id}"else"not matched"end#=> "not matched"
In addition to pinning local variables, you can also pin instance, global, and class variables:
$gvar =1classA@ivar =2@@cvar =3case [1,2,3]in^$gvar,^@ivar,^@@cvar"matched"else"not matched"end#=> "matched"end
You can also pin the result of arbitrary expressions using parentheses:
a =1b =2case3in^(a+b)"matched"else"not matched"end#=> "matched"
Matching non-primitive objects:deconstruct anddeconstruct_keys¶↑
As already mentioned above, array, find, and hash patterns besides literal arrays and hashes will try to match any object implementingdeconstruct (for array/find patterns) ordeconstruct_keys (for hash patterns).
classPointdefinitialize(x,y)@x,@y =x,yenddefdeconstructputs"deconstruct called" [@x,@y]enddefdeconstruct_keys(keys)puts"deconstruct_keys called with #{keys.inspect}" {x:@x,y:@y}endendcasePoint.new(1,-2)inpx,Integer# sub-patterns and variable binding works"matched: #{px}"else"not matched"end# prints "deconstruct called""matched: 1"casePoint.new(1,-2)inx:0..=>px"matched: #{px}"else"not matched"end# prints: deconstruct_keys called with [:x]#=> "matched: 1"
keys are passed todeconstruct_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**rest pattern is used,nil is passed as akeys value:
casePoint.new(1,-2)inx:0..=>px,**rest"matched: #{px}"else"not matched"end# prints: deconstruct_keys called with nil#=> "matched: 1"
Additionally, when matching custom classes, the expected class can be specified as part of the pattern and is checked with===
classSuperPoint<PointendcasePoint.new(1,-2)inSuperPoint(x:0..=>px)"matched: #{px}"else"not matched"end#=> "not matched"caseSuperPoint.new(1,-2)inSuperPoint[x:0..=>px]# [] or () parentheses are allowed"matched: #{px}"else"not matched"end#=> "matched: 1"
These core and library classes implement deconstruction:
Guard clauses¶↑
if can be used to attach an additional condition (guard clause) when the pattern matches incase/in expressions. This condition may use bound variables:
case [1,2]ina,bifb==a*2"matched"else"not matched"end#=> "matched"case [1,1]ina,bifb==a*2"matched"else"not matched"end#=> "not matched"
unless works, too:
case [1,1]ina,bunlessb==a*2"matched"else"not matched"end#=> "matched"
Note that=> andin operator can not have a guard clause. The following examples is parsed as a standalone expression with modifierif.
[1,2]ina,bifb==a*2
Appendix A. Pattern syntax¶↑
Approximate syntax is:
pattern: value_pattern | variable_pattern | alternative_pattern | as_pattern | array_pattern | find_pattern | hash_patternvalue_pattern: literal | Constant | ^local_variable | ^instance_variable | ^class_variable | ^global_variable | ^(expression)variable_pattern: variablealternative_pattern: pattern | pattern | ...as_pattern: pattern => variablearray_pattern: [pattern, ..., *variable] | Constant(pattern, ..., *variable) | Constant[pattern, ..., *variable]find_pattern: [*variable, pattern, ..., *variable] | Constant(*variable, pattern, ..., *variable) | Constant[*variable, pattern, ..., *variable]hash_pattern: {key: pattern, key:, ..., **variable} | Constant(key: pattern, key:, ..., **variable) | Constant[key: pattern, key:, ..., **variable]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"inb"matched"inc"not matched"enda#=> undefinedc#=> undefined
Number ofdeconstruct,deconstruct_keys method calls:
$i =0ary = [0]defary.deconstruct$i+=1selfendcasearyin [0,1]"not matched"in [0]"matched"end$i#=> undefined