Ruby ‘Dig’ Hashes
A thorough examination of Ruby’s ‘dig’ method
Today, I want to talk a bit about a little-known method in Ruby language that works on both Arrays and Hashes called #dig
.
Basic Usage
Let's say we have a hash as follows:
In the above, we have a hash containing some personal information if we want to access a specific data element with standard data accessing behavior as below.
As you can see normal data access works fine until for some reason hash did not contain the relevant key it would be throwing errors. This is an issue when working with changing data hash structures such as responses of APIs. For such a situation, if we were to make validations to check whether the key is available to fetch it would be long, not readable, and would be a not good way of writing code.
Using the #dig
method we can accomplish that in a concise way and overall it would help to write better code.
Using the #dig
method it will call itself (#dig
method) at each step of the way and return nil if any intermediate step is nil.
Advance Usage
Now we have a much more complex hash structure like the below one.
Here, as I mentioned that arrays are also able to respond to #dig
method we are able to access each of the array elements in the above nested as well. Shown below are a few ways both hash and array can be used with #dig
method.
Erroneous Usage
Using #dig
rather than normal data traversing through a hash or array is better, it also has erroneous usage scenarios. As mentioned above in the article when #dig
given a list of parameters each of that elements would be called with #dig
itself. For some reason if the selected item does not respond_to?
the #dig
method it will return a error.
Altogether there are six built-in Ruby classes that have method #dig
, three in the core classes and three in the standard library.
In the core:
Array#dig: the first argument is an Integer index.
Hash#dig: the first argument is a key.
Struct#dig: the first argument is a key.
In the standard library:
OpenStruct#dig: the first argument is a String name.
CSV::Table#dig: the first argument is an Integer index or a String header.
CSV::Row#dig: the first argument is an Integer index or a String header.
Need to learn more about the #dig
method? Read the following articles as well:
I will be bringing these kinds of exciting articles where I explore nuggets throughout the Ruby ecosystem. Follow me now for a thrilling ride through all things Ruby 💎🤗
LinkedIn: https://www.linkedin.com/in/randika-banura/
Github: https://github.com/randikabanura