Back to blog

Blog

Ruby ‘Dig’ Hashes

A thorough examination of Ruby’s ‘dig’ method

Jun 19, 2023 · ruby, ruby-on-rails, software-engineering, advanced-programming, programming
Ruby ‘Dig’ Hashes
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 (#digmeth...

The full article is published on Medium.

Read on Medium