DEV Community

Sahil
Sahil

Posted on

4

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

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay