7

loop { break }可以正常工作,但是

block = Proc.new { break }
# or
# block = lambda { break }
loop(&block) # => LocalJumpError: break from proc-closure

有可能break在一个block variable

更新:

一个解释更多的例子:

def odd_loop
    i = 1
    loop do
        yield i
        i += 2
    end
end

def even_loop
    i = 2
    loop do
        yield i
        i += 2
    end
end

# This work
odd_loop do |i|
    puts i
    break if i > 10
end

# This doesn't work
break_greater_10 = Proc.new do |i|
    puts i
    break if i > 10
end

odd_loop(&break_greater_10) # break from proc-closure (LocalJumpError)
even_loop(&break_greater_10) # break from proc-closure (LocalJumpError)

根据我的理解,Proc.new应该与块相同(它可以是块中return的函数),但我不明白为什么不能打破循环。

PS对不起我的英语不好>~<

4

2 回答 2

7

To solve this problem you could

raise StopIteration

this worked for me.

于 2015-02-05T15:54:25.717 回答
3

要从块中返回,您可以使用next关键字。

def foo
  f = Proc.new {next ; p 1}
  f.call
  return 'hello'
end

puts foo     # => 'hello' , without 1
于 2013-03-15T10:14:28.737 回答