【问题标题】:Is there a functional version of begin...rescue...end (exception block) in ruby?ruby 中是否有 begin...rescue...end(异常块)的功能版本?
【发布时间】:2011-02-15 16:19:06
【问题描述】:

我想在 ruby​​ 中做这样的事情:

safe_variable = begin
  potentially_nil_variable.foo
rescue
  some_other_safe_value
end

... 并将异常块(开始/救援/结束)视为函数/块。这不像写的那样工作,但有没有办法得到类似的结果?

注意我实际上在做的是这个,它有效但 IMO 丑陋:

begin
  safe_variable = potentially_nil_variable.foo
rescue
  safe_variable = some_other_safe_value
end

更新

我想我在 ruby​​ 语法上遇到了一个极端情况。我实际上在做的是这样的:

object_safe = begin potentially_nil_variable.foo
rescue ""
end

错误是class or module required for rescue clause。可能它认为""应该是异常结果的占位符。

【问题讨论】:

  • 您的第一个示例实际上应该按照书面形式运行 - 您遇到什么错误?
  • 奇怪的是,功能版本似乎没有出现在 ruby​​ 文档的任何地方。

标签: ruby exception functional-programming


【解决方案1】:

我所知道的向可能为 nil 的对象发送消息的最实用的方法是 andand。对于 nil,andand 返回一个对象,无论您发送什么消息,它都会简单地返回 nil。对于其他对象,它返回原始对象。几乎任何事情都会比处理异常更有效。

【讨论】:

    【解决方案2】:

    您应该使用的表格:

    safe_variable = begin
      potentially_nil_variable.foo
    rescue
      some_other_safe_value
    end
    

    更短的形式:

    safe_variable = this_might_raise rescue some_other_safe_value
    

    如果你只是避免nil,你可以查看ActiveRecord的try

    safe_variable = potentially_nil_variable.try(:foo) || some_other_safe_value
    

    【讨论】:

      猜你喜欢
      • 2016-04-10
      • 2013-02-01
      • 2019-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-05
      • 2017-08-13
      • 1970-01-01
      相关资源
      最近更新 更多