0013 Dig

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 ».

0013-dig_1.png

The advantages of dig over the [] method:

  • Readability
  • Returns nil if the path doesn’t exist

0013-dig_2.png

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!

0013-dig_3.png

Link to Ruby documentation for dig with a dedicated page.