Skip to content

End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

Hash#dig

hash.dig(key, *identifiers) → object

Finds and returns the object in nested objects that is specified by key and identifiers. The nested objects may be instances of various classes. See Dig Methods.

Nested Hashes:

Example
h = {foo: {bar: {baz: 2}}}
h.dig(:foo) # => {:bar=>{:baz=>2}}
h.dig(:foo, :bar) # => {:baz=>2}
h.dig(:foo, :bar, :baz) # => 2
h.dig(:foo, :bar, :BAZ) # => nil

Nested Hashes and Arrays:

Example
h = {foo: {bar: [:a, :b, :c]}}
h.dig(:foo, :bar, 2) # => :c

This method will use the default values for keys that are not present:

Example
h = {foo: {bar: [:a, :b, :c]}}
h.dig(:hello) # => nil
h.default_proc = -> (hash, _key) { hash }
h.dig(:hello, :world) # => h
h.dig(:hello, :world, :foo, :bar, 2) # => :c
See also #delete_if #each #delete #each_key also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.0