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.
79437edc07125851d702c4e8b29f969b?d=identicon&s=25 Talha Oktay (Guest)
on 2006-03-30 20: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.
2e34f386b20cb7c11c4204d699babd78?d=identicon&s=25 Chris Alfeld (Guest)
on 2006-03-30 20: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
Bc6d88907ce09158581fbb9b469a35a3?d=identicon&s=25 James Britt (Guest)
on 2006-03-30 21:01
(Received via mailing list)
Talha Oktay 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
A9c4658e9e475e13d790ae419acf01b6?d=identicon&s=25 Simon Kröger (Guest)
on 2006-03-30 22:08
(Received via mailing list)
Talha Oktay 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.