Need a pick?
The dig
method is not only defined in Hash
, but also in Array
, Struct
, … It can be used to extract an element from a treelike object by specifying the « path ».
The advantages of dig
over the []
method:
- Readability
- Returns
nil
if the path doesn’t exist
Last but not least, dig
doesn’t care what type of object it is when traversing the « path ». It just needs to respond to the dig
method, which allows it to mix types… perfect for JSON!
Link to Ruby documentation for dig
with a dedicated page.