Safe navigation equivalent to Rails try for hashes

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

    While hash&.[](:key) is elegant to the trained rubyist, I'd just use hash && hash[:key] as it reads better and more intuitively for the programmer coming after me, who may not be as familiar with the intricacies of ruby. Some extra characters in the codebase can sometimes save a whole lot of googling for someone else.

    (Given the context you want to use this in is in a conditional statement, of course.)

提交回复
热议问题