Skip to content
instance method

Hash#dig

(K, *untyped) -> untyped
dig(key, *identifiers) → object

Finds and returns an object found in nested objects, as 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

If no such object is found, returns the hash default:

Example
h = {foo: {bar: [:a, :b, :c]}}
h.dig(:hello) # => nil
h.default_proc = -> (hash, _key) { hash }
h.dig(:hello, :world)
# => {:foo=>{:bar=>[:a, :b, :c]}}

Related: Methods for Fetching.

See also #delete_if #each #delete #each_key also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0