Today I Learned

hashrocket A Hashrocket project

Sorting Map Keys with `inspect/2` in Elixir

Elixir maps don't guarantee key ordering, so inspecting a map can produce an unexpected output:

iex(1)> %{c: 3, a: 2, b: 1, f: %{c: 3, a: 2, b: 1}} |> inspect()
"%{c: 3, f: %{c: 3, b: 1, a: 2}, b: 1, a: 2}"

Today I learned we can pass sort_maps: true via custom_options to inspect/2 to get alphabetically sorted keys and this applies to nested maps too:

iex(2)> %{c: 3, a: 2, b: 1, f: %{c: 3, a: 2, b: 1}} |> inspect(custom_options: [sort_maps: true])
"%{a: 2, b: 1, c: 3, f: %{a: 2, b: 1, c: 3}}"

This is particularly useful when writing tests or diffing output where consistent key ordering matters.

See More #elixir TILs
Looking for help? At Hashrocket, we 💜 Elixir! From our many Elixir client projects, to sponsoring the Chicago Elixir Meetup, to the source code for this application, we are invested in this community. Contact us today to talk about your Elixir project.