randombits
randombits

Reputation: 48450

Break out of ruby inner block using catch/throw

I am interested in breaking out of both the outer and inner block if an exception is thrown in an inner ruby block. The code might look something like this:

catch "ExitBlock" do
      foo.each_with_index do |el, idx|
        bar = ... // do more stuff, 
        bar.each_with_index do |el1, idx1|
          if some_bad_stuff
            throw "ExitBlock"
          end
        end
      end
    end

if some_bad_stuff is true, it should exit both the outer block and the inner block, not just the inner block. the code above is giving me an ArgumentError however with:

ArgumentError: uncaught throw "ExitBlock"

What am I doing wrong?

Upvotes: 1

Views: 952

Answers (2)

pizen
pizen

Reputation: 474

It would be much cleaner to just break out of the loop rather than bringing exceptions into the mix:

foo.each_with_index do |el, idx|
    bar = ... // do more stuff, 
    break_outer = false
    bar.each_with_index do |el1, idx1|
        if some_bad_stuff
            break_outer = true
            break
        end
    end
    if break_outer
        break
    end
end

Upvotes: 0

megas
megas

Reputation: 21791

It works with symbols:

catch :exit_block do
  foo.each_with_index do |el, idx|
    bar = ... // do more stuff, 
    bar.each_with_index do |el1, idx1|
      if some_bad_stuff
        throw :exit_block
      end
    end
  end
end

But the documentation says "[argument] can be an arbitrary object, not only Symbol"

I have no idea what's going on.

Upvotes: 2

Related Questions