Project

General

Profile

Actions

Feature #18384

open

Pattern Match Object

Added by baweaver (Brandon Weaver) almost 3 years ago. Updated over 2 years ago.

Status:
Open
Assignee:
-
Target version:
-
[ruby-core:106444]

Description

Related to discussion in #18369 it might be nice to have a literal syntax for constructing a single pattern match case outside of a one-liner.

Years ago in Qo I had done this via === to enable syntax like this:

list_of_people.select(&Qo[first_name: /^F/, last_name: /r$/, age: 20..40])

This is valid Ruby, but the pattern match syntax itself cannot be used outside of a literal match, making this impossible without syntax changes.

Proposal

My proposal would be a case which would be very useful in predicate methods (any?, all?, etc) and triple-equals responding methods (select, reject, grep, etc):

list_of_people.select(&pattern(
  first_name: /^F/,
  last_name: /r$/,
  age: 20..40 
))

...in which pattern would be substituted with a more appropriate name which I cannot think of at the moment.

Portability

Now the reason I think this could be very interesting is the portability of patterns. Consider the potential of making a PatternMatch object much like a Regular Expression:

TARGET_PERSON = PatternMatch.new(first_name: 'something')
list_of_people.select(&TARGET_PERSON)

As they can serve similar purposes of giving an expressive language to query against known structures I can see this making sense. The challenge is that the initialization of such an object would need to be special to accommodate the pattern matching syntax, adding more complicated parsing rules.

This behavior might be consistent with Proc, RegExp, and Range-like behavior.

ActiveRecord-like

This gets very close to the classic ActiveRecord where pattern:

People.where(age: 20..30)

Potential Issues

Now this is not without potential issue, as must be highlighted. The first, as just mentioned, is the ActiveRecord syntax and potentially overloading that and keyword arguments:

People.where(age: 20..30)

Without a clear signifier this could make parsing much more difficult.

Current Viable Workarounds

It also must be mentioned that this is currently possible:

list_of_people.select { _1 in { first_name: 'something' } }

...though the requirement of explicit braces feels a tinge verbose, I understand why they're present.

I think this is an acceptable compromise at the moment, but feel we're very close to an interesting syntactic breakthrough.

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0