Unexpected Return (LocalJumpError)

前端 未结 1 1084
隐瞒了意图╮
隐瞒了意图╮ 2020-12-08 04:17

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 > Ration         


        
相关标签:
1条回答
  • 2020-12-08 05:03

    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.

    0 讨论(0)
提交回复
热议问题