在 Ruby 中,您可以在赋值结束时编写 rescue
以捕获可能出现的任何错误。我有一个函数(如下:a_function_that_may_fail
),如果不满足某些条件,让它抛出错误很方便。以下代码运行良好
post = {}
# Other Hash stuff
post['Caption'] = a_function_that_may_fail rescue nil
但是,如果函数失败,我什至不希望设置 post['Caption']。
我知道我能做到:
begin
post['Caption'] = a_function_that_may_fail
rescue
end
但这感觉有点过分 - 有更简单的解决方案吗?
最佳答案
问题是优先级。最简单的解决方案:
(post['Caption'] = a_function_that_may_fail) rescue nil
不过,像这样改变优先级有点深奥。如果您可以重写您的 a_function_that_may_fail
以在失败时返回 nil
可能会更好。
您还可以使用临时变量并测试是否为零:
caption = a_function_that_may_fail rescue nil
post['Caption'] = caption unless caption.nil?
一个非常小的区别是,如果 a_function_that_may_fail
没有引发异常但返回了 nil
,这不会设置 post['Caption']
.
关于ruby - `var = something rescue nil` 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2621749/