Our two HYP coins® — Ruby on Rails — Hash dig method

HYP
hypsters
Published in
2 min readAug 30, 2019

Hi there!

We’re starting a new series called Our two HYP coins® to share stuff that we find useful to a developer or a designer’s life.

For our first post we are sharing about a method we found when working on a Ruby on Rails project. The problem that we were trying to solve at the time was accessing a value inside a hash without using a large number of if conditions to check if there was a value for that key. For example:

infinity_war = { thanos: { armor: 1, gauntlet: { stones: 1 } } }

To find out how many stones Thanos has on the gauntlet we could do this:

infinity_war[:thanos][:gauntlet][:stones] # => 1

But imagine we were trying to find out how many stones there were with the following hash:

infinity_war = { thanos: { armor: 1 } }
infinity_war[:thanos][:gauntlet][:stones]
# => NoMethodError (undefined method `[]' for nil:NilClass)

To solve this issue we needed to first verify if Thanos exists, then if the gauntlet exists, etc. We would end up with a somewhat inefficient code:

if infinity_war[:thanos].present? && infinity_war[:thanos][:gauntlet].present?
infinity_war[:thanos][:gauntlet][:stones]
end

This didn’t feel right, and if we had more nested keys and values this could become tedious and hard to read. So we abandoned this solution and thought of another approach to solve this.

What if we tried to surround that line with a begin .. rescue?

begin
infinity_war[:thanos][:gauntlet][:stones]
rescue NoMethodError
nil
end

This could solve our problem… but was this the better way? There is so much that Ruby can help us with, there had to be a way to do this with a helper or a method.

That’s when we found the method dig!

infinity_war = { thanos: {armor: 1, gauntlet: {stones: 1}}}
infinity_war.dig(:thanos, :gauntlet, :stones)
# => 1infinity_war = { thanos: {armor: 1}}
infinity_war.dig(:thanos, :gauntlet, :stones)
# => nil

This method solved our problem in a cleaner way and did exactly what we wanted.

We hope this will help you in the future and we’ll try to publish more of these ‘small developer life hacks’ to improve your projects!

Obrigado!

--

--