【问题标题】:Why LocalJumpError? [duplicate]为什么是 LocalJumpError? [复制]
【发布时间】:2012-01-10 23:52:40
【问题描述】:

可能重复:
Using 'return' in a Ruby block

我是 Ruby 新手,很惊讶这个 sn-p raise 一个 LocalJumpError 当块 return:

$bail_if = proc { |condition|
  if condition
    puts 'the condition is true'
    return
  else
    puts 'the condition is false'
  end
}

def method some_condition
  $bail_if[some_condition]
end

method true

如果我在def method中将bail_if定义为局部变量,那么就没有问题了。这是为什么呢?

【问题讨论】:

  • 在 ruby​​ 1.8.7 上为我工作。你在运行 ruby​​ 1.9 吗?
  • 糟糕,忘了说我使用的是 1.9.2p290。谢谢!
  • 您问这个是因为如果some_condition 为真,您希望method 返回,否则继续运行method 方法的其余部分?顺便说一句,method 不是一个理想的名字,因为已经有a method called method
  • @Squeegy:这是因为proc 在 1.8 和 1.9 中的行为不同 - 在 1.8 中它返回一个 lambda,而在 1.9 中它返回一个 proc。见要点 2 here
  • @AndrewGrimm,是的,我问这个是因为如果some_condition 为真,我希望method 返回,否则继续运行method 的其余部分。

标签: ruby block


【解决方案1】:

将您的 proc { |condition| 更改为 lambda { |condition|。 proc-object 具有块语义,而 lambda 对象具有方法语义。因为 proc 对象就像一个块,所以当您调用执行 return 语句的 proc 时,它会尝试从包含已转换为 proc 的块的方法返回。在第一种情况下您没有这种方法,因此您得到LocalJumpError。当您在方法中将 proc 定义为局部变量时,一切正常。

【讨论】:

  • 它不会抛出异常,但我认为它不会做 OP 想要做的事情。
【解决方案2】:

您不会在 ruby​​ 1.9 中使用 proc(也称为块)return。摆脱那个明确的return 似乎可以解决它。但无论如何,return 在这里完全没用。

或者,如果您确实需要显式返回,请使用 lambda,而不是像 @WarHog 建议的那样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-23
    • 2015-01-05
    • 1970-01-01
    • 2011-11-18
    • 2012-03-27
    • 1970-01-01
    • 1970-01-01
    • 2019-11-15
    相关资源
    最近更新 更多