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:
parent
f1035248af
commit
fa87f72e1e
Notes:
git
2021-07-16 01:56:27 +09:00
5 changed files with 79 additions and 2 deletions
|
@ -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
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue