1
0
Fork 0
mirror of https://github.com/ruby/ruby.git synced 2022-11-09 12:17:21 -05:00

Add pattern matching pin support for instance/class/global variables

Pin matching for local variables and constants is already supported,
and it is fairly simple to add support for these variable types.

Note that pin matching for method calls is still not supported
without wrapping in parentheses (pin expressions).  I think that's
for the best as method calls are far more complex (arguments/blocks).

Implements [Feature #17724]
This commit is contained in:
Jeremy Evans 2021-05-13 15:31:46 -07:00
parent f1035248af
commit fa87f72e1e
Notes: git 2021-07-16 01:56:27 +09:00
5 changed files with 79 additions and 2 deletions

View file

@ -312,6 +312,33 @@ One important usage of variable pinning is specifying that the same value should
end
#=> "not matched"
In addition to pinning local variables, you can also pin instance, global, and class variables:
$gvar = 1
class A
@ivar = 2
@@cvar = 3
case [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 = 1
b = 2
case 3
in ^(a + b)
"matched"
else
"not matched"
end
#=> "matched"
== Matching non-primitive objects: +deconstruct+ and +deconstruct_keys+
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).
@ -449,7 +476,10 @@ Approximate syntax is:
value_pattern: literal
| Constant
| ^variable
| ^local_variable
| ^instance_variable
| ^class_variable
| ^global_variable
| ^(expression)
variable_pattern: variable