DEV Community

Subash
Subash

Posted on

Ruby - dig method

The dig method is a useful tool to dig through all the keys of a given hash (recursively) and returns the value. If the value for final key or the intermediate key is not found a nil value is returned

Let's say we have the given params

params = Hash.new
params[:user1] = {
  name: 'Alice',
  gender: 'F',
  age: '40',
  job_details: {
    company: 'XYZ'
  },
  contact_details: {
    Landline: '00000000',
    mobile: '0000001'
  }
}
params[:user2] = {
  name: 'Bob',
  gender: 'M',
  age: '40',
  job_details: {
    company: 'ABC'
  }
}
Enter fullscreen mode Exit fullscreen mode

Now if we need the mobile number of all users, the following code will break because in case of Bob the contact_details hash is not available.

params.map{|key,value| value[:contact_details][:mobile]}
Enter fullscreen mode Exit fullscreen mode

So we need to check if the key is available before diving into it. If there are more iterations then there would be more conditional checks. Luckily there is an alternative
We can use dig to fetch with single line of code as the dig handles the conditional checks internally. The code will look like this and it will work for both users

params.map{|key,value| value.dig(:contact_details, :mobile)}
Enter fullscreen mode Exit fullscreen mode

which will give the following output

=> ["0000001", nil]
Enter fullscreen mode Exit fullscreen mode

dig iterated through the given keys recursively, if any of the keys are not available it will break returning nil (as in case of Bob).

Note: In scenarios where an error should be raised when a key is not found, dig will not be helpful as it returns nil.

Source

Top comments (0)