Pattern matching on maps

To use pattern matching on a map, we set our pattern with the key-value pairs we want to match on, as you can see in the following example:

iex> %{"name" => name, "age" => age} = %{"name" => "Gabriel", "age" => 1}%{"age" => 1, "name" => "Gabriel"}iex> name"Gabriel"iex> age1

Note that in this case we're matching on all keys of the map, but this isn't necessarywe could just match on age, for instance. However, your pattern may only contain keys that exist on the map that's being matched on, otherwise MatchError will be raised.

Sometimes, you may want to match on the value of a variable, instead of rebinding it to a new value. To this end, you can use the pin operator, represented by the ^ character:

iex> name = "Gabriel" ...

Get Mastering Elixir now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.