意外返回(LocalJumpError) [英] Unexpected Return (LocalJumpError)
问题描述
这段 Ruby 2.0 代码有什么问题?
What is the problem with this Ruby 2.0 code?
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
错误位于 block (2 levels) in <main>':意外返回 (LocalJumpError)
.我想创建一个包含 n 个(以及其余的零)的平面列表,其中 n 是分母低于 8 且介于 1/3 和 1 之间的有理数的个数/2.(这是一个 Project Euler 问题).所以我试图从内部块返回.
The error is in block (2 levels) in <main>': unexpected return (LocalJumpError)
. I want to create a flat list containing n ones (and the rest zeroes) where n is 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.
推荐答案
你不能在 Ruby 的块内return
*.最后一条语句成为返回值,因此您可以删除案例中的返回语句:
You can't return
inside a block in Ruby*. The last statement becomes the return value, so you can just remove the return statements in your case:
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
*:你可以在 lambda
块内: lambda { return "foo" }.call # =>foo"
.它与范围和所有这些有关,这是 lambda
块和 proc
块之间的主要区别之一.您传递给方法的普通"块更像是 proc
块.
*: You can inside lambda
blocks: lambda { return "foo" }.call # => "foo"
. It has to do with scoping and all that, and this is one of the main differences between lambda
blocks and proc
blocks. "Normal" blocks you pass to methods are more like proc
blocks.
这篇关于意外返回(LocalJumpError)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!