【问题标题】:`var = something rescue nil` behaviour`var = 拯救 nil` 的行为
【发布时间】:2011-02-06 23:35:28
【问题描述】:

在 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

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

【问题讨论】:

  • 重写函数并不是一个真正的选项,它是一个 Nokogiri 搜索——本质上,如果有特定的 XML 元素,我想设置“Caption”哈希项,但重要的是,如果不设置它那个 XML 元素不存在。

标签: ruby exception-handling


【解决方案1】:

确保您的方法返回nilfalse

def this_may_fail
  some_logic rescue nil
end

然后您可以使用 if 修饰符检查您的方法的返回值,并仅在它不是 nilfalse 时才分配该值:

post['Caption'] = this_may_fail if this_may_fail

如果您不想为 if 条件和赋值调用两次方法,也可以将 this_may_fail 的返回值缓存在一个局部变量中。

the_value = this_may_fail
post['Caption'] = the_value if the_value

还要注意rescue 修饰符只捕获StandardError 及其子类。

【讨论】:

    【解决方案2】:

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

    (post['Caption'] = a_function_that_may_fail) rescue nil
    

    不过,像这样更改优先级有点深奥。如果您可以重写您的 a_function_that_may_fail 以在失败时返回 nil 可能会更好。

    您也可以使用临时变量并测试是否为 nilness:

    caption = a_function_that_may_fail rescue nil
    post['Caption'] = caption unless caption.nil?
    

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

    【讨论】:

    • (...) 救援 nil 并不是那么深奥,恕我直言。它也很容易阅读。
    【解决方案3】:
    post.store('Caption', a_function_that_may_fail) rescue nil
    

    【讨论】:

    • 可爱,但如果不是 post['Caption']= 而是 local_var=,则不适用。我更喜欢 molf 的“深奥”解决方案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 2015-02-15
    • 2013-06-28
    • 1970-01-01
    • 2011-04-15
    • 2010-10-07
    相关资源
    最近更新 更多