summaryrefslogtreecommitdiff
path: root/doc
diff options
context:
space:
mode:
authorJeremy Evans <code@jeremyevans.net>2021-05-13 15:31:46 -0700
committerJeremy Evans <code@jeremyevans.net>2021-07-15 09:56:02 -0700
commitfa87f72e1e84e2b55516be188f00434a683b924c (patch)
tree0c4efbae462e0ebae46447ea0e18bbea4d7821f0 /doc
parentf1035248af04b2a4d58990740c3f1b840a5eac78 (diff)
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]
Notes
Notes: Merged: https://github.com/ruby/ruby/pull/4502
Diffstat (limited to 'doc')
-rw-r--r--doc/syntax/pattern_matching.rdoc32
1 files changed, 31 insertions, 1 deletions
diff --git a/doc/syntax/pattern_matching.rdoc b/doc/syntax/pattern_matching.rdoc
index 69756369fb..49835def22 100644
--- a/doc/syntax/pattern_matching.rdoc
+++ b/doc/syntax/pattern_matching.rdoc
@@ -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