`var = something rescue nil`行为

JP.*_*JP. 8 ruby exception-handling

在Ruby中,您可以rescue在分配结束时编写一个代码来捕获可能出现的任何错误.我有一个函数(下面a_function_that_may_fail:),如果不满足某些条件,它会让它抛出一个错误.以下代码运行良好

post = {}
# Other Hash stuff
post['Caption'] = a_function_that_may_fail rescue nil
Run Code Online (Sandbox Code Playgroud)

但是如果函数失败,我想发帖['Caption']甚至没有设置.

我知道我能做到:

begin
  post['Caption'] = a_function_that_may_fail
rescue
end
Run Code Online (Sandbox Code Playgroud)

但感觉有点过分 - 是否有更简单的解决方案?

mol*_*olf 22

问题是优先的.最简单的解决方案:

(post['Caption'] = a_function_that_may_fail) rescue nil
Run Code Online (Sandbox Code Playgroud)

不过,改变这样的优先级有点深奥.如果失败可以重写你a_function_that_may_fail的返回可能会更好nil.

您还可以使用临时变量并测试nilness:

caption = a_function_that_may_fail rescue nil
post['Caption'] = caption unless caption.nil?
Run Code Online (Sandbox Code Playgroud)

一个非常小的区别是,post['Caption']如果a_function_that_may_fail没有引发异常但返回,则不会设置nil.