How to break out deeply nested loops? (newbie)


#1

I sometimes need to break out, next or redo deeply nested loops in
different
levels instead of the innermost enclosing scope. Is there a facility to
label blocks or loops and redo, next or break to the labeled blocks or
loops as in some other programming languages?

Thanks in advance.


#2

Not nicely.

This is discussed in the Pickaxe. For example

catch “BreakOuterLoop” do
for i in 1…10
print “out #{i}\n”
for j in 1…10
print “in #{j}\n”
throw “BreakOuterLoop” if i+j > 16
end
end
end


#3

Talha O. wrote:

I sometimes need to break out, next or redo deeply nested loops in different
levels instead of the innermost enclosing scope. Is there a facility to
label blocks or loops and redo, next or break to the labeled blocks or
loops as in some other programming languages?

Thanks in advance.

throw/catch

http://www.ruby-doc.org/core/classes/Kernel.html#M001972


#4

Talha O. schrieb:

I sometimes need to break out, next or redo deeply nested loops in different
levels instead of the innermost enclosing scope. Is there a facility to
label blocks or loops and redo, next or break to the labeled blocks or
loops as in some other programming languages?

Thanks in advance.

You may use throw, catch or continuations (for the fun of it) or just
wrap some of your inner loops in their own method and use return.
(i prefer the last version most of the time)

cheers

Simon