Safe navigation equivalent to Rails try for hashes

In Rails, you can do hash.try(:[], :key) which helps if hash is potentially nil. Is there an equivalent version for using the new Ruby 2.3 safe navigation operator &. with []?


&. is not equivalent to Rails' try, but you can use &. for hashes. Just use it, nothing special.

hash[:key1]&.[](:key2)&.[](:key3)

Although I would not do that.


Ruby 2.3 and later

There's Hash#dig method now that does just that:

Retrieves the value object corresponding to the each key objects repeatedly.

h = { foo: {bar: {baz: 1}}}

h.dig(:foo, :bar, :baz)           #=> 1
h.dig(:foo, :zot)                 #=> nil

http://ruby-doc.org/core-2.3.0_preview1/Hash.html#method-i-dig

Pre Ruby 2.3

I usually had something like this put into my intializer:

Class Hash
    def deep_fetch *args
      x = self
      args.each do |arg|
        x = x[arg]
        return nil if x.nil?
      end
      x
    end
end

and then

response.deep_fetch 'PaReqCreationResponse', 'ThreeDSecureVERes', 'Message', 'VERes', 'CH', 'enrolled'

in one wacky case.

The general consensus in the community seems to be to avoid both try and the lonely operator &.