Feature #18384


Pattern Match Object

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

Target version:


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:[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.


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):
  first_name: /^F/,
  last_name: /r$/,
  age: 20..40 
)) which pattern would be substituted with a more appropriate name which I cannot think of at the moment.


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 = 'something')

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.


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: { _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.


Also available in: Atom PDF