Skip to content

Commit

Permalink
Document named captures
Browse files Browse the repository at this point in the history
  • Loading branch information
Earlopain committed Oct 16, 2024
1 parent 97a3b51 commit 375a82c
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions docs/modules/ROOT/pages/node_pattern.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ Ruby code with a method call with two integer literals as arguments, `foo(1, 2)`
To match just those method calls where the first argument is a literal `1`, use `(send nil? :foo (int 1) int)`.
Any child that is a node can be a target for nested matching.

[#any-single-node]
== `_` for any single node

`_` will check if there's something present in the specific position, no matter the
Expand Down Expand Up @@ -314,6 +315,37 @@ The following pattern will have two captures, both arrays:
(send nil? $int+ (send $...))
----

Captures <<any-single-node, for any single node>> can be given a name to make them more descriptive:

----
(send nil? $_method_name)
----

You can also reference them later in the pattern to match against the value that was previously captured:

----
(pair
(_ $_key)
(_ $_key))
----

This will match hash pairs where the key is equal to the value.

[source,ruby]
----
# Matches:
{ a: :a } # (hash
# (pair
# (sym :a)
# (sym :a)))
# But not this:
{ a: :b } # (hash
# (pair
# (sym :a)
# (sym :b)))
----

== `^` for parent

One may use the `^` character to check against a parent.
Expand Down Expand Up @@ -347,6 +379,7 @@ we can write:
This would match both of these methods `foo` and `bar`, even though
these `return` for `foo` and `bar` are not at the same level.

[source,ruby]
----
def foo # (def :foo
return 42 # (args)
Expand Down

0 comments on commit 375a82c

Please sign in to comment.