TIL: Elixir maps have built in syntax for updating

By: Marin Abernethy

I am relatively new to Elixir and often find there are numerous ways to implement a single task. For example, when I want to update a key value in a map, I have several options before me…

Given, expenses = %{groceries: 200, rent: 1000, commute: 70}, I could employ:

Map.merge(expenses, %{
  rent: 1200,
  comcast: 100
})
Map.put(expenses, :booze, 100)
Map.update(expenses, :misc, 300, &(&1 * 2))
expenses = %{groceries: %{milk: 5}, apartment: %{rent: 1000, comcast: 100}}
put_in(expenses, [:rent, :comcast], "too much")

However, today I learned, maps come with a built in syntax for updating one or more key values!

 %{expenses | groceries: 150, commute: 75}

While a bit obscure, and not easily found in the elixir docs, this trick is definitely nice to have in my elixir tool belt. The only thing to remember is that this syntax requires groceries and commute to already exist. Otherwise, it will fail with an error. Hopefully, this syntax comes in handy for you now too!

If you want to know more about how to deal with nested structures, check out Brian’s post “Elixir Best Practices - Deeply Nested Maps”!