Sandip Mane
by Sandip Mane
~1 min read

Categories

  • Ruby

#dig method was added in Ruby 2.3 to Array and Hash classes. It makes digging the Array and Hash easy while making the code readable.

Dig in Arrays

Dig in arrays works with a sequence of indexes, when an element is not present at any given index, it returns nil instead of raising errors.

> array = [
  [11, 22, 33],
  [21, 22, 23],
  [31, 32, 33]
]

> array.dig(0, 0)
=> 11

> array.dig(2, 1)
=> 32

> array.dig(3, 0)
=> nil

Dig in Hashes

Dig in hashes works with a sequence of keys, when any given key is not present, it returns nil instead of raising errors.

> params = {
  name: "John Doe",
  profile_attributes: {
    age: 28,
    address_attributes: {
      country: "Canada",
      city: "Toronto"
    }
  }
}

> params.dig(:profile_attributes, :address_attributes, :city)
=> "Toronto"

At first, it looks simple and straight forward which it is, what it saves us from is the following check which is often there at the API endpoints.

params[:profile_attributes]
  && params[:profile_attributes][:address_attributes]
  && params[:profile_attributes][:address_attributes][:city]

Finally,

In this post, we checked how we could make use of ruby’s #dig method to make code more readable while querying unknown objects.

And as always, thanks for reading!😃