Safe navigation equivalent to Rails try for hashes

后端 未结 5 1297
深忆病人
深忆病人 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:34

    Accepted answer will not account for when hash is nil...

    You can rewrite what you have using the safe nav operator before the .try and that will work

    hash&.try(:[], :key)

    but you can also use:

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

    A way you could do this on a hash is by doing...

    hash&.dig(:key1, :key2 ...)
    

    which will return nil if any key fetch isn't present.

    { key1: { key2: 'info' } } 
    

    would return 'info'

    { key1: { wrong_key: 'info' } } 
    

    would return nil

提交回复
热议问题