← All languages
Ruby method of the day
Random

dig

Access nested elements safely without raising errors.

Description

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.

Arguments

NameDescriptionOptional
key, ... A sequence of keys or indices for each nesting level. No

Example

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

Reference