Safe navigation equivalent to Rails try for hashes

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

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

提交回复
热议问题