Access nested elements safely without raising errors.
The dig method extracts a nested value from a structure of arrays, hashes, or other objects that respond to dig. It takes a sequence of keys or indices and navigates through each level, returning nil if any intermediate value is nil.
This is much safer than chaining [] calls, which would raise a NoMethodError if an intermediate value is nil. It works across mixed structures — for example, digging through a hash that contains arrays.
Introduced in Ruby 2.3, dig is available on Array, Hash, Struct, and OpenStruct. Custom classes can support it by implementing a dig method.
| Name | Description | Optional |
|---|---|---|
key, ... |
A sequence of keys or indices for each nesting level. | No |
data = {a: {b: {c: 42}}}
data.dig(:a, :b, :c) # 42
data.dig(:a, :x, :c) # nil
arr = [[1, [2, 3]]]
arr.dig(0, 1, 0) # 2