From: "Eregon (Benoit Daloze) via ruby-core" Date: 2024-02-12T12:54:46+00:00 Subject: [ruby-core:116677] [Ruby master Feature#16828] Introduce find patterns Issue #16828 has been updated by Eregon (Benoit Daloze). An easy way to understand the "backtracking" of find pattern is it works like `each_slice(n)` and doesn't actually backtrack. So its performance is linear to the number of elements of the array being matched. https://github.com/ruby/ruby/commit/ddded1157a90d21cb54b9f07de35ab9b4cc472e1#diff-a5ba41b51e3655f9f244362a616282b5119d3e15dd6c52ee999bbdfcc5b86a77 has nice Ruby pseudo-code describing how it works. ---------------------------------------- Feature #16828: Introduce find patterns https://bugs.ruby-lang.org/issues/16828#change-106690 * Author: ktsj (Kazuki Tsujimoto) * Status: Closed * Priority: Normal * Assignee: ktsj (Kazuki Tsujimoto) ---------------------------------------- I propose to add find pattern to pattern matching. # Specification ``` find_pattern: Constant(*var, pat, ..., *var) | Constant[*var, pat, ..., *var] | [*var, pat, ..., *var] ``` This pattern is similar to array pattern, except that it finds the first match values from the given object. ```ruby case ["a", 1, "b", "c", 2, "d", "e", "f", 3] in [*pre, String => x, String => y, *post] p pre #=> ["a", 1] p x #=> "b" p y #=> "c" p post #=> [2, "d", "e", "f", 3] end ``` Note that, to avoid complexity, the proposed feature doesn't support backtracking. Thus, the following code raises a NoMatchingPatternError. ```ruby case [0, 1, 2] in [*, a, *] if a == 1 end ``` # Implementation * https://github.com/k-tsj/ruby/tree/find-pattern-prototype -- https://bugs.ruby-lang.org/ ______________________________________________ ruby-core mailing list -- ruby-core@ml.ruby-lang.org To unsubscribe send an email to ruby-core-leave@ml.ruby-lang.org ruby-core info -- https://ml.ruby-lang.org/mailman3/postorius/lists/ruby-core.ml.ruby-lang.org/