7

loop { break } can work fine, but

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

Is it possible to break in a block variable ?

Update:

A example to explain more:

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)

As my comprehension, Proc.new should work same as block (it can return a function from block), but I don't understand why can't break a loop.

P.S. Sorry for my bad english >~<

3
  • What do you want to achieve with this? Commented Mar 15, 2013 at 10:06
  • 99% related: stackoverflow.com/questions/626/… Commented Mar 15, 2013 at 10:43
  • @Sergio See update, @tokland I know the different in Proc.new and lambda, I am asking break in closure Commented Mar 15, 2013 at 10:55

2 Answers 2

7

To solve this problem you could

raise StopIteration

this worked for me.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 Not only does it work, it's actually used in an example in the ruby docs to halt a loop.
3

To return from a block you can use the next keyword.

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

puts foo     # => 'hello' , without 1

3 Comments

break a outside loop is different return from block
In your case, you can use lambda and use return, I think next is not good for this (although it works)
This doesn't actually work to halt a loop as the OP asked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.