January 2024
Intermediate to advanced
718 pages
20h 15m
English
Often data isn’t simply a single hash or array but comes in a complex package that combines hashes and arrays. Accessing data in a complicated structure can be a pain, but Ruby provides a shortcut with the dig method.
The dig method, which is defined for Array, Hash, and Struct, allows you to “dig” through a complicated data structure in a single command.
| | data = { |
| | mcu: [ |
| | {name: "Iron Man", year: 2010, actors: ["Robert Downey Jr.", "Gwyneth Paltrow"]} |
| | ], |
| | starwars: [ |
| | {name: "A New Hope", year: 1977, actors: ["Mark Hamill", "Carrie Fisher"]} |
| | ] |
| | } |
| | data[:mcu][0][:actors][1] # => "Gwyneth Paltrow" |
| | data.dig(:mcu, 0, :actors, 1) # => "Gwyneth Paltrow" |
The biggest advantage of using dig ...
Read now
Unlock full access