Today I Learned

A Hashrocket project

Elixir Pattern Matching with Variables

Let’s say you have a variable that you want to pattern match.

By default Elixir won’t use the variable’s value to do the pattern matching and it will do a regular assignment, overriding the original variable’s value:

iex(1)> year = 2020
2020

iex(2)> car = %{year: 2019}
%{year: 2019}

iex(3)> %{year: year} = car
%{year: 2019}

iex(4)> year
2019

Elixir has the pin opertator ^ that does exactly what we need. So in our example we can use the pin operator and if it doesn’t match you get an error:

iex(1)> year = 2020
2020

iex(2)> car = %{year: 2019}
%{year: 2019}

iex(3)> %{year: ^year} = car
** (MatchError) no match of right hand side value: %{year: 2019}
Looking for help? Elixir is quickly gaining momentum for web applications that need concurrency, performance, and the ability to connect to many different clients. The developers at Hashrocket are learning along with the rest of the development community that Elixir and Phoenix are viable Rails alternatives for the right application. Check out the source code for Today I Learned, written in Elixir, and contact us if you need help with your Elixir project.