From: "zeke (Zeke Gabrielse)" Date: 2022-08-10T16:46:26+00:00 Subject: [ruby-core:109465] [Ruby master Feature#18961] Introduce support for pattern matching all elements of an array Issue #18961 has been reported by zeke (Zeke Gabrielse). ---------------------------------------- Feature #18961: Introduce support for pattern matching all elements of an array https://bugs.ruby-lang.org/issues/18961 * Author: zeke (Zeke Gabrielse) * Status: Open * Priority: Normal ---------------------------------------- When pattern matching arrays, often times we want to assert that a given array's elements all match a pattern. For example: ```ruby class Robot; end class User; end case [User.new, User.new] in [User, *] => u if u.all? { _1 in User } puts 'array of users!' end # => array of users! case [User.new, User.new, Robot.new] in [User, *] => u if u.all? { _1 in User } puts 'array of users!' end # => Error: guard clause does not return true (NoMatchingPatternError) ``` I propose an improved syntax for matching an array's elements: ```ruby case [User.new, User.new] in [User*] puts 'array of users!' end ``` Putting the `*` on the right-hand side differentiates the syntax from the array Splat operator. Another option would be `**`, or perhaps using a range `User..`. Not only is the pattern more readable, it also allows these constraints to be expressed in single line pattern matching: ```ruby [User.new, User.new] => [User*] => arr # => [#, #] [User.new, Robot.new] => [User*] => arr # => [#, #] does not return true (NoMatchingPatternError) [User.new, User.new, Robot.new] => [User*, Robot] => arr # => [#, #, #] [User.new, User.new] in [User*] # => true [User.new, Robot.new] in [User*] # => false ``` It allows single line pattern matching to express similar constraints to `case in`, since guard clauses are not available for single line pattern matching: ```ruby [User.new, User.new] in [User, *] => u if u.all? { _1 in User } # => undefined method `all?' for nil:NilClass (NoMethodError) ``` -- https://bugs.ruby-lang.org/ Unsubscribe: