Ruby 2.7 — Pattern Matching — First Impressions

The code’s merged, nightly build is on the way, and I’m a rather impatient writer who wants to check out the new presents.

This is my first pass over pattern matching, and there will be more detailed articles coming out as I have more time to experiment with the features.

To be clear: This article will meander as it’s a first impression.

I’ll be running more tests on it tomorrow, but wanted to write something on it tonight to see how well first impressions matched up.

The Short VersionThis is going to be a long article, and the short version isn’t going to cover even a small portion of it.

Each major section will have a single style it covers.

The test file covers a good portion of this if you want an at-a-glance read:ruby/rubyThe Ruby Programming Language [mirror].

Contribute to ruby/ruby development by creating an account on GitHub.

github.

comLiteral MatchesMuch like a regular case statement, you can perform literal matches:case 0in 0 then trueelse falseend# => trueIn these cases it would probably be best to use when instead.

The difference is that if there’s no match it’s going to raise a NoMatchingPattern error rather than returning nil like case / when statements would.

Multiple MatchersIn typical case statements, a comma would be used, but with some of the new syntax this would break some of the destructuring that will be mentioned later:case 0in 0 | 1 trueend# => trueIn the case of captured variables below, they can’t be mixed:case 0in a | 0end# Error: illegal variable in alternative patternCaptured VariablesOne of the more interesting additions is captured variables:case truein a aend# => trueIn Guard ClausesThese can also be used in suffix conditionals or rather guard type clauses in what’s reminiscent of Haskell:case 0in a if a == 0 trueend# => trueIn Assignment MappingsThey can even be assigned with a Hash-like syntax:case 0in 0 => a a == 0endWith PlaceholdersMost interesting in this section is that they appear to treat underscores as a special placeholder:case 0in _ | _a trueendThough this could also be seen as a literal variable assignment, it’s an interesting riff on Scala’s pattern matching wildcards.

DestructuringInterestingly you can shadow the variables as well while destructuring an array:case [0, 1]in a, a a == 1end# => trueIt appears that the last assignment will be a in this case, and that commas are now used for destructuring rather than for denoting a separate pattern to match against as is the case for when.

DeconstructIn the top of the file there’s a class defined:class C class << self attr_accessor :keys end def initialize(obj) @obj = obj end def deconstruct @obj end def deconstruct_keys(keys) C.

keys = keys @obj endendIt appears to indicate a way to define how an object should be destructured by pattern matching:[[0, 1], C.

new([0, 1])].

all?.do |i| case i in 0, 1 true endendincluding accounting for unbalanced matches:[[0], C.

new([0])].

all?.do |i| case i in 0, 1 else true endendI don’t understand how deconstruct_keys is working, but it feels really odd to me from first glance.

With SplatsIt also will capture multiple arguments like destructuring currently works on Ruby arrays:case []in *a a == []endcase [0, 1, 2]in *a, 1, 2 a == [0]endMeaning that * could also be used as a bit of a wildcard:case 0in * trueendOn HashesThese appear to work a lot like keyword arguments:case {a: 0}in a: 0 trueendThat also means that kwsplats could be used here:case {}in **a a == {}end…and with the keywords bit above, that means that classes could define their own destructuring using keywords, but I’m not clear on that.

I’m really hoping that this also uses === on each param, but the tests don’t indicate this.

I’ll be experimenting with this later.

Triple EqualsLike our current case statements, it appears that the new method of pattern matching uses === for comparisons:case 'abc'in /a/ trueendcase 0in -> i { i == 0 } trueendCombined with DestructuringOne thing I enjoyed in Qo was the ability to match against another array using === to write queries.

It looks like the new syntax will compare each element and give us something very similar:case [0, 1, 2, 3, 4, 5]in [0.

1, 0.

2, 0.

, 0.

, (.

5), (.

5)] trueendIt’s amusing that they’ve included beginningless and endless ranges in the example, as that could be very useful later on.

I certainly hope these work with hashes, as I really really really want this to work:case objectin method_a: 0.

10, method_b: String trueend…because if we can define our own deconstructors just imagine the possibilities there.

The class attr for keys is odd though, not sure what to think of that one.

Pin OperatorI’m going to have to come back to this one as I do not understand it.

I assume it means not to assign and to “pin” a variable so it doesn’t get overwritten:a = /a/case 'abc'in ^a trueendcase [0, 0]in a, ^a a == 0endI believe this can be used to capture one element in a variable and also reference it later like a back-reference of sorts.

Thoughts?This hasn’t built with Nightly yet, so I intend to make a second pass on this after it clears to verify some behavior I have suspicions about.

Mostly I want to see about the hash matchers, as there’s some amazing potential there.

Going to be digging through and playing with this over the next few weeks, here’s the next post in the series:Ruby 2.

7 — Pattern Matching — Destructuring on PointNow that pattern matching has hit Ruby Nightly as an experimental feature, let’s take a look into some potential…medium.

com.

. More details

Leave a Reply