Safe navigation equivalent to Rails try for hashes

后端 未结 5 1353
深忆病人
深忆病人 2021-02-06 20:13

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

5条回答
  •  半阙折子戏
    2021-02-06 20:54

    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 &.

    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

提交回复
热议问题