Welcome to day 26 of the 49 Days of Ruby! 🎉
Patterns! Today we are going to discuss the exciting topic of pattern matching in Ruby.
Pattern matching is a relatively new phenomenon in the language. It was introduced in Ruby 2.7, and further enhancements have continued through to the Ruby 3.0 major release.
What is pattern matching?
Pattern matching is searching for a given sequence.
It allows for matching inside objects for a specific content structure.
Pattern matching can be a very helpful tool and offers you a lot of powerful utility as you build out applications!
Pattern matching in Ruby
How do we implement pattern matching in Ruby?
The basic structure is the following for a pattern matching statement:
case statement
in pattern ...
...
in pattern ...
...
else
...
end
It starts with the statement or expression that we are matching against: case [1, 2]
Let's take a look at an example from Woman on Rails:
case [1, 2]
in [2, a]
:no_match
in [1, a]
:match
end
# => :match
> a
# => 2
In the above example, we are matching against an array of two integers. We look for two versions of that array: [2, a]
and [1, a]
.
The array we're matching against fits the second in
clause. Thus, when we match against a
, the return value is 2
.
Another great example is matching inside of a hash:
case { coffee: "Americano", tea: "Earl Gray" }
in { coffee: "Americano", tea: "Green" }
:no_match
in { coffee: "Americano", tea: x }
:match
end
# => :match
> x
# => "Americano"
There is so much more to learn about pattern matching in Ruby! Check out the Ruby docs to see a lot more examples of use cases!
That's it for today. See you tomorrow!
Come back tomorrow for the next installment of 49 Days of Ruby! You can join the conversation on Twitter with the hashtag #49daysofruby.
Top comments (0)