Is there an Elixir equivalent for Hash#Dig in Ruby ?
Ruby dig example
h = { foo: {bar: {baz: 1}}}
h.dig(:foo, :bar, :baz) #=> 1
h.dig(:foo, :zot) #=> nil
Use Kernel.get_in/2
:
iex(1)> m = %{foo: %{bar: %{baz: 1}}}
%{foo: %{bar: %{baz: 1}}}
iex(2)> get_in m, [:foo, :bar, :baz]
1
iex(3)> get_in m, [:foo, :zot]
nil
get_in
works fine with maps. To make something that works with both maps and structs, you have to make it yourself:
def dig(nil, _), do: nil
def dig(struct, []), do: struct
def dig(struct, [head | tail]) do
struct
|> Map.get(head)
|> dig(tail)
end
> m = %{foo: %{bar: %{baz: 1}}}
> dig m, [:foo, :bar, :baz]
1
> dig m, [:foo, :zot]
nil
> dig m, [:foo, :zot, :qux]
nil
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With