Safe navigation equivalent to Rails try for hashes

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

    A rather more legible way to use the safe navigation operator than using hash&.[](:slug) is to use the fetch method:

    hash&.fetch(:slug)
    

    If your key may not be defined, you can use the second argument as a default:

    hash&.fetch(:slug, nil)
    

提交回复
热议问题