Ruby Oneline救援 [英] Ruby Oneline Rescue

查看:93
本文介绍了Ruby Oneline救援的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近了解到,可以在一行代码上使用rescue,以防该行出现问题(请参阅

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 #21). I have some code that used to look like this:

if obj['key'] && obj['key']['key2'] && obj['key']['key2']['name']
  name = obj['key']['key2']['name']
else
  name = ''
end

通过rescue方法,我相信我可以将代码更改为如下形式:

With the rescue method, I believe I can change that code into something like this:

name = obj['key']['key2']['name'] rescue ''

如果在访问散列的任何级别上抛出nil异常,它都应该被救援捕获并给我",这就是我想要的.如果这是所需的行为,我也可以选择将名称设置为nil.

If a nil exception is thrown at any level of accessing the hash, it should get caught by the rescue and give me '', which is what I want. I could also choose to set name to nil if that were the desired behavior.

这样做有任何已知的危险吗?我问,因为这似乎太真实了.我有这么丑陋的代码,我想摆脱它,就像第一个代码示例一样.

Is there any known danger in doing this? I ask because this seems too good to be true. I have so much ugly code that I'd love to get rid of that looks like the first code example.

推荐答案

读起来不错!但这会影响您的表现.以我的经验,rescue在被触发时要慢得多,而在没有触发时会稍慢.在所有情况下,if都更快.要考虑的另一件事是,不应预期到异常,并且您对此代码有点类似.将哈希表嵌套得如此之深可能是一种好味道,以至于重构是不必要的

Reads good! But it will hit your performance. In my experience rescue is much slower when triggered and slightly slower when it's not. In all cases the if is faster. Other thing to consider, is that exceptions shouldn't be expected and you kind of are with this code. Having a hash so deeply nested might be a good smell that a refactoring is nede

这篇关于Ruby Oneline救援的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆