liveBook · Manning

Array#dig

As explained in The Well-Grounded Rubyist, Fourth Edition

Hash#dig is a Ruby Hash method that traverses nested hashes using a sequence of keys and returns the value at the resulting path.

Array#dig retrieves a value from an array nested inside another array by accepting the index of each level as an argument. It provides a compact alternative to chaining bracket access such as arr[3][0]. section 9.2.2

Reading through nested arrays

Given arr = [[1], 2, 3, [4, 5]], arr[3][0] returns 4. The equivalent arr.dig(3, 0) also returns 4. Each argument identifies the index to follow at the corresponding nesting level. For deeper structures, supply additional indexes, as in [["Joe", %w(loves Lucy,), "his"], "adorable", ["daughter"]].dig(0, 1, 1), which returns "Lucy,". section 9.2.2

Use Array#dig when nested array access would otherwise require a growing chain of [] calls. Its place among common array methods is specifically retrieving nested elements, while ordinary indexing retrieves a single element and values_at retrieves several selected elements. section 9.2.2

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains the argument-to-index mapping and contrasts dig with chained [] access, stopping short of implementation internals.
Examples
Uses nested numeric arrays and a deeply nested array containing names and words.
What it assumes
Assumes array indexing and nested-array structure while demonstrating both from concrete examples.
What you can do after
Apply it via Ruby to retrieve values from nested arrays with one argument per nesting level.
How it connects
Connects nested arrays with array indexing, multidimensional arrays, and Hash#dig.

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.