Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
476 views
in Technique[技术] by (71.8m points)

ruby - Unexpected Return (LocalJumpError)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

*: 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...