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.