Dig Methods

Ruby’sdig methods are useful for accessing nested data structures.

Consider this data:

item = {id:"0001",type:"donut",name:"Cake",ppu:0.55,batters: {batter: [      {id:"1001",type:"Regular"},      {id:"1002",type:"Chocolate"},      {id:"1003",type:"Blueberry"},      {id:"1004",type:"Devil's Food"}    ]  },topping: [    {id:"5001",type:"None"},    {id:"5002",type:"Glazed"},    {id:"5005",type:"Sugar"},    {id:"5007",type:"Powdered Sugar"},    {id:"5006",type:"Chocolate with Sprinkles"},    {id:"5003",type:"Chocolate"},    {id:"5004",type:"Maple"}  ]}

Without adig method, you can write:

item[:batters][:batter][1][:type]# => "Chocolate"

With adig method, you can write:

item.dig(:batters,:batter,1,:type)# => "Chocolate"

Without adig method, you can write, erroneously (raisesNoMethodError (undefined method `[]' for nil:NilClass)):

item[:batters][:BATTER][1][:type]

With adig method, you can write (still erroneously, but avoiding the exception):

item.dig(:batters,:BATTER,1,:type)# => nil

Why Isdig Better?

How Doesdig Work?

The call sequence is:

obj.dig(*identifiers)

Theidentifiers define a “path” into the nested data structures:

Adig method raises an exception if any receiver does not respond to #dig:

h = {foo:1 }# Raises TypeError (Integer does not have #dig method):h.dig(:foo,:bar)

What Else?

The structure above has Hash objects and Array objects, both of which have instance methoddig.

Altogether there are six built-in Ruby classes that have methoddig, three in the core classes and three in the standard library.

In the core:

In the standard library: