ruby 意外返回(LocalJumpError)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17800629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 06:05:22  来源:igfitidea点击:

Unexpected Return (LocalJumpError)

rubyruby-2.0

提问by Eli Rose -- REINSTATE MONICA

What is the problem with this Ruby 2.0 code?

这个 Ruby 2.0 代码有什么问题?

p (1..8).collect{|denom|
    (1...denom).collect{|num|
        r = Rational(num, denom)
        if r > Rational(1, 3) and r < Rational(1, 2)
            return 1
        else
            return 0
        end
    }
}.flatten

The error is in block (2 levels) in <main>': unexpected return (LocalJumpError). I want to create a flat list containing nones (and the rest zeroes) where nis the number of rational numbers with denominators below 8 which are between 1/3 and 1/2. (it's a Project Euler problem). So I'm trying to return from the inner block.

错误在block (2 levels) in <main>': unexpected return (LocalJumpError). 我想创建一个包含n个(以及其余的零)的平面列表,其中n是分母低于 8 且介于 1/3 和 1/2 之间的有理数的个数。(这是一个 Project Euler 问题)。所以我试图从内部块返回。

回答by sarahhodne

You can't returninside a block in Ruby*. The last statement becomes the return value, so you can just remove the return statements in your case:

您不能return在 Ruby * 中的块内。最后一条语句成为返回值,因此您可以删除案例中的返回语句:

p (1..8).collect{|denom|
    (1...denom).collect{|num|
        r = Rational(num, denom)
        if r > Rational(1, 3) and r < Rational(1, 2)
            1
        else
            0
        end
    }
}.flatten

*: You can inside lambdablocks: lambda { return "foo" }.call # => "foo". It has to do with scoping and all that, and this is one of the main differences between lambdablocks and procblocks. "Normal" blocks you pass to methods are more like procblocks.

*:您可以在lambda块内:lambda { return "foo" }.call # => "foo". 它与范围和所有这些有关,这是lambda块和proc块之间的主要区别之一。您传递给方法的“普通”块更像是proc块。