I often times find myself in situations where I need to rename one or more 
keys in a Map, when for instance, converting from Strings to Atoms:

new_map = %{
  foo: Map.fetch!(old_map, "foo"),
  bar: Map.fetch!(old_map, "bar"),
  ...
}

or otherwise taking a Map from one part of the system and renaming keys to 
make it work in another part of the system:

new_map = %{
  user_id: post.author_id,
  content: post.body,
  ...
}

With a Map.rename_key/3 function, we could instead write: 

new_map =
  old_map
  |> Map.rename_key("foo", :foo)
  |> Map.rename_key("bar", :bar)
  ...

or:

new_map =
  post
  |> Map.rename_key(:user_id, :author_id)
  |> Map.rename_key(:body, :content)
  ...

In the situation that you're performing a bulk update of key names (as 
seems to be implied above), Map.rename_keys/3 makes more sense:

new_map = Map.rename_keys(old_map, %{"foo" => :foo, "bar" => :bar, ...})

or:

new_map = Map.rename_keys(post, %{author_id: :user_id, body: :content, ...})

With the Map.rename_key[s]/3 functions, the intent is very explicit, and 
induces less cognitive load to understand.

Renaming Map keys is a situation I run into at least monthly, and I do 
wonder whether the rest of the community has this problem as well so as to 
make it a worthwhile addition.

-- 
You received this message because you are subscribed to the Google Groups 
"elixir-lang-core" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to elixir-lang-core+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/elixir-lang-core/70108df1-6c5e-475b-8dbd-b4222e920e0bo%40googlegroups.com.

Reply via email to