Skip to content

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

instance method

Struct#dig

dig(name, *identifiers) → object
dig(n, *identifiers) → object

Finds and returns an object among nested objects. The nested objects may be instances of various classes. See Dig Methods.

Given symbol or string argument name, returns the object that is specified by name and identifiers:

Example
Foo = Struct.new(:a)
f = Foo.new(Foo.new({b: [1, 2, 3]}))
f.dig(:a) # => #<struct Foo a={:b=>[1, 2, 3]}>
f.dig(:a, :a) # => {:b=>[1, 2, 3]}
f.dig(:a, :a, :b) # => [1, 2, 3]
f.dig(:a, :a, :b, 0) # => 1
f.dig(:b, 0) # => nil

Given integer argument n, returns the object that is specified by n and identifiers:

Example
f.dig(0) # => #<struct Foo a={:b=>[1, 2, 3]}>
f.dig(0, 0) # => {:b=>[1, 2, 3]}
f.dig(0, 0, :b) # => [1, 2, 3]
f.dig(0, 0, :b, 0) # => 1
f.dig(:b, 0) # => nil
See also #deconstruct_keys #each #deconstruct #each_pair also in 4.1 · 4.0 · 3.4 · 3.3 · 3.1 · 3.0