【问题标题】:Ruby: why rescue block value instead of ensure block?Ruby:为什么救援块值而不是确保块?
【发布时间】:2019-10-03 14:52:17
【问题描述】:

Ruby 方法通常返回最后执行的块的值,就像这样:

def boom
    if false
        "a"
    else
        "double a"
    end
end

p boom # "double a"

但是当我创建包含rescueensure 的化合物时。 ensure 是执行的最后一个块,但会返回来自 rescue 块的值。为什么会这样?

def a
    1.some_weird_method
    "Boom"
rescue NoMethodError
    p "An Error: " + $!.message
ensure
    p "This  value must be returned"
end

p "Why do rescue block returns?:" + a
p RUBY_VERSION

输出是:

Finished in 44 ms
"An Error: undefined method `some_weird_method' for 1:Integer"
"This  value must be returned"
"Why do rescue block returns?:An Error: undefined method `some_weird_method' for 1:Integer"
"2.4.6"

可以在这里测试代码:https://leetcode.com/playground/2NPL8QgN

【问题讨论】:

  • 因为这就是 Ruby 的实现方式(我认为这样更有意义)。 ensure 不管成功还是失败都会跑,所以你最终可能会吃掉你真正关心的东西。
  • (请注意,如果您要返回对某些内容的引用,您仍然可以修改所引用的内容,尽管我不会这样做,因为这会导致一些认知开销。)

标签: ruby exception


【解决方案1】:

ensure 默认不改变返回值。你可以通过在ensure 中显式调用return 来绕过它,不过我还没有经常看到这种模式(如果有的话)。

http://blog.leshill.org/blog/2009/11/17/ensure-with-explicit-return.html

【讨论】:

    猜你喜欢
    • 2012-02-26
    • 2023-01-13
    • 2015-03-07
    • 1970-01-01
    • 2014-03-06
    • 2013-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多