Better Programming

Advice for programmers.

Follow publication

Member-only story

How to and When to Use Pattern Matching in Ruby

Gernot Gradwohl
Better Programming
Published in
5 min readJan 26, 2022

Photo by JJ Ying on Unsplash

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?

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Gernot Gradwohl
Gernot Gradwohl

Written by Gernot Gradwohl

Passionate programmer. Love the elegance of Ruby. Recently started to dig into functional programming with Elixir.

No responses yet

Write a response