Ruby Oneline Rescue

后端 未结 2 1271
遇见更好的自我
遇见更好的自我 2021-02-18 18:58

I recently learned that you can use rescue on a line of code in case something goes wrong on that line (see http://www.rubyinside.com/21-ruby-tricks-902.html Tip #2

2条回答
  •  执念已碎
    2021-02-18 19:53

    This specific example can now be achieved with Ruby 2.3's dig method.

    name = obj.dig 'key', 'key2', 'name'
    

    This will safely access obj['key']['key2']['name'], returning nil if any step fails.

    (In general, it's usually advised to use exceptions only for real, unanticipated, errors, though it's understandable in an example like this if the syntax makes it cumbersome.)

提交回复
热议问题