Updating a Map

Maps let us add new key/value entries and update existing entries without traversing the whole structure. But as with all values in Elixir, a map is immutable, and so the result of the update is a new map.

The simplest way to update a map is with this syntax:

 new_map = %{ old_map | key => value, ​​ }

This creates a new map that is a copy of the old, but the values associated with the keys on the right of the pipe character are updated:

 iex>​ m = %{ ​a:​ 1, ​b:​ 2, ​c:​ 3 }
 %{a: 1, b: 2, c: 3}
 iex>​ m1 = %{ m | ​b:​ ​"​​two"​, ​c:​ ​"​​three"​ }
 %{a: 1, b: "two", c: "three"}
 iex>​ m2 = %{ m1 | ​a:​ ​"​​one"​ }
 %{a: "one", b: "two", c: "three"}

However, this syntax will not add a new key to a map. To do this, you have ...

Get Programming Elixir ≥ 1.6 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.