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(map1, map2)
if I want to update multiple key value pairs and/or several new ones
Map.merge(expenses, %{
rent: 1200,
comcast: 100
})
Map.put(map, key, val)
if updating or adding a single key value
Map.put(expenses, :booze, 100)
Map.update(map, key, initial, fun)
: if I want to increment a value by a certain degree
Map.update(expenses, :misc, 300, &(&1 * 2))
Kernel.put_in(data, keys, value)
: if I want to update a value in a nested structure
expenses = %{groceries: %{milk: 5}, apartment: %{rent: 1000, comcast: 100}}
put_in(expenses, [:apartment, :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”!