Skip to content

Instantly share code, notes, and snippets.

@themusicman
Created June 5, 2019 13:35
Show Gist options
  • Save themusicman/47842c95022e0e8d37c6d9522f6dca25 to your computer and use it in GitHub Desktop.
Save themusicman/47842c95022e0e8d37c6d9522f6dca25 to your computer and use it in GitHub Desktop.
Updating Maps in Elixir
# A map in Elixir is a key => value data structure
thomas = %{first_name: "Thomas", age: 38, job_title: "Director of Awesome"}
# There are multiple ways to update a Map in Elixir like
# put/3 - https://hexdocs.pm/elixir/Map.html#put/3
thomas = Map.put(thomas, :age, 39)
%{first_name: "Thomas", age: 39, job_title: "Director of Awesome"}
# merge/2 - https://hexdocs.pm/elixir/Map.html#merge/2
thomas = Map.merge(thomas, %{age: 39})
%{first_name: "Thomas", age: 39, job_title: "Director of Awesome"}
# put_in/3 - https://hexdocs.pm/elixir/Kernel.html#put_in/3
thomas = put_in(thomas, [:age], 39)
%{first_name: "Thomas", age: 39, job_title: "Director of Awesome"}
# One of may favorites is
thomas = %{thomas | age: 39}
# just be sure if you use this way to update the map that they keys already exist in the map you are updating otherwise you will get an error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment