Labeled break, next, and redo in Ruby
Many languages support breaking out of nested loops. There are some typical ways of doing this:
- Some languages can name loops by providing a label for the loop. In those languages, you can use
breaktogether with a label to specify which loop to break out of. Examples: Perl, Java, JavaScript, and some others. - Some languages can specify the number of layers of loops to break out of. In those languages, you can use
breaktogether with a number to specify how many layers of loops to break out of. The only example that I know is C#. - Some languages have
gotostatements. You can easily break from loops to wherever you want by usinggoto(actually breaking out of nested loops is among the only recommended cases for usinggoto). Examples: C, C++.
However, in most other languages, it is not easy to break out of nested loops. A typical solution is this:
1
2
3
4
5
6
7
8
9
10
|
|
In languages with exceptions, another possible workaround is to use exceptions (the catch–throw control flow):
1
2
3
4
5
6
7
|
|
I wrote a simple module to better use this workaround.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
|
Example usage:
1
2
3
4
5
6
7
8
9
|
|