Forum: Ruby How to break out deeply nested loops? (newbie)

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Talha O. (Guest)
on 2006-03-30 22:18
(Received via mailing list)
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.
Chris A. (Guest)
on 2006-03-30 22:55
(Received via mailing list)
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
James B. (Guest)
on 2006-03-30 23:01
(Received via mailing list)
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
Simon Kröger (Guest)
on 2006-03-31 00:08
(Received via mailing list)
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
This topic is locked and can not be replied to.