Thursday 19 January 2017

Extract values from hash or array with .dig method in ruby 2.3

Suppose that we have a hash some think like this -

place ={
   country:{
      state:{
         district:"Katihar"
      }
   }
}


For access the district value we are doing like this -

place[:country][:state][:district]

It is working fine but there is a problem, suppose that if the state key is nil than it will return something like this-

#NoMethodError: undefined method `[]' for nil:NilClass

We can handle above error in rails by doing like this -

place.try(:[], :country).try(:[], :state).try(:[], :district)

But this is looking somewhat ugly isn't it?

Now, here comes ruby 2.3 with .dig method. The new #dig method can look for deeply nested keys-

place.dig(:country, :state, :district)

If any of the attempts to access a nested key is nil, the output will be nil.

4 comments: