DEV Community

Sahil
Sahil

Posted on

Use DIG save headache

Lets assume we send a request and get the following response as JSON

user = {
  user: {
    address: {
      street: '123 Some street'
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Now in order to get the street address, the simplest way would be street = user[:user][:address][:street] but what if address is empty or even the user object is empty.

In order to avoid the error sometimes we end up writing code which looks like

if user[:user] && user[:user][:address] && user[:user][:address][:street]
 street = user[:user][:address][:street]
end
Enter fullscreen mode Exit fullscreen mode

The above code is valid, but looks quite ugly. With ruby a less known functionality is hash.dig. As mentioned in ruby docs dig Retrieves the value object corresponding to the each key objects repeatedly.

So, if we use dig in the above example it becomes

 street = user.dig(:user, :address, :street) || 'Default Street'

Enter fullscreen mode Exit fullscreen mode

Cheers

Top comments (0)