如果条件在 ruby 中,“rescue false”是什么意思

野村海苔

我是红宝石新手,有一个问题。

if (new_account.save rescue false)
   # when account save success
else
   # when account save has error
end

我不确定在这段代码中救援错误是什么意思。谢谢

最大限度

单行救援是语法糖

foo.bar rescue false
# same as
begin
  foo.bar
rescue
  false
end

所以你的代码和这个差不多

result = nil
begin
  result = new_account.save
rescue
  result = false
end

if result
  # when account save success
else
  # when account save has error
end

rescue false意味着内部抛出的异常被new_account.save视为与返回相同false在我看来,这是糟糕的设计new_account显然设计为有两种不同的失败情况,但调用代码忽略了它。此代码极有可能隐藏保存方法中发生的实际错误。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章