Member-only story
How to and When to Use Pattern Matching in Ruby
Pattern matching lets us write declarative code that is easy to maintain and reason about. Let’s see how we can use this in Ruby

One big feature that was added recently into Ruby is pattern matching. Pattern matching was already added in Ruby 2.7 and was improved since then.
A lot has been talked about recent additions to Ruby's release but not so much about pattern matching, which is a shame in my opinion since this adds so much to our options as Rubyist’s. So, let’s change this.
In this blog post, we will discuss what pattern matching is, when it can be used, and also we’ll make a small benchmark where we will compare it to a similar if
statement.
What is Pattern Matching
In Wikipedia pattern matching is explained as “the act of checking a given sequence of tokens for the presence of the constituents of some pattern”. For me this didn’t explain a lot, so let’s look at an actual example.
For many Rubyist’s, including myself, pattern matching was made known with the rise of Elixir. With the help of this feature Elixir is able to overload functions.
This way a function is very small and can handle just one case where another function handles another input argument. It also makes it possible to write very readable code to handle error cases. How does this look like? Let’s look at an overloaded function:
The argument of the function valid_password?
is deconstructed and pattern matched. The BEAM (the VM that Elixir runs on) checks what form the argument has and then calls the right function. So, if the argument is a Map AND has the key hashed_password
then the first function is called else the other one.
How does it look like for error handling in Elxir?