What is Pattern Matching in Ruby 2.7 ?

Tram Ho

1. What is Pattern Matching?

Pattern matching is a way of defining a pattern for our data, and if the data matches that pattern, we can do something with the data according to this pattern. And we can say, with pattern matching we obtain specific parts of data selected on specified rules.
In this presentation we can also find a sentence, that for Ruby pattern matching is a case/when with a multiple assignment.

In the ruby Pattern Matching is shown via the case statement , however it is not accompanied by when but paired with in as you can below:

The processing of the patterns, they are run in the order with normal case until we find the first match. When no case there will be no pattern was found, else will be executed. we will get NoMatchingPatternError when no case was found.

2. Basic Pattern

2.1 Value Pattern

Now in statmant case we number 10 and at in statment we put range number as 1..100 as below:

As you can see the out put should be: it is match! . what happend when we put number 101 in in statmant case as below? :

When the matching fails it outputs a NoMatchingPatternError followed by the tested object inside a parenthesis.

2.2 Variable Pattern

For variable pattern, you can use it to show value that you compare in statment.


Not only value or variable but we can also use pattern with array. Now let’s see the code below:

Also with array patterns, we can go decoding arrays


As Pattern will assign the value to the variable immediately after the pattern with the => if it matches that pattern. We can also bind the variable to a value using as pattern. It can be useful when we need more complex assignments..
This pattern is quite useful for developers to check match condition.Now you can check example below:

2.5 Hash Pattern

Hash pattern is similar to array pattern. It is not only use for hash object but we can use it with specific rule with its.

Hash patterns are more flexible than array matches, by default they always test for subsets.

Share the news now

Source : Viblo