Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir map dig functionality like Ruby Hash#Dig

Tags:

elixir

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
like image 221
elpddev Avatar asked May 04 '16 12:05

elpddev


2 Answers

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
like image 158
Dogbert Avatar answered Oct 19 '22 17:10

Dogbert


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
like image 22
denis.peplin Avatar answered Oct 19 '22 17:10

denis.peplin