On Wed, Feb 19, 2014 at 1:59 PM, [email protected] wrote:
In general, it is considered bad practice to use exceptions for flow
control.
Exceptions indicate, and should be used for, cases where something
unexpected happened and you are trying to recover.
These are no exceptions. Notice this:
Exceptions: raise…rescue
Flow control: catch…throw
I strongly encourage you not to use them in this way.
In Ruby this was invented intentionally to allow for such kind of flow
control. I agree, one should use is sparingly but there are situations
where it comes handy. Personally I can’t remember the last time I used
it
though.
The have seen several good alternatives to your problem:
* flatten the array and use one loop
* make a method and use return
There’s also another one
irb(main):001:0> a=[[1,2,3],[2,3,4],[54,6,5]]
=> [[1, 2, 3], [2, 3, 4], [54, 6, 5]]
irb(main):002:0> a.each {|i| i.each {|j| p j; break if j == 2} or break}
1
2
=> nil
Works also if the element is not found in the first sub array:
irb(main):006:0> a.each {|i| i.each {|j| p j; break if j == 4} or break}
1
2
3
2
3
4
=> nil
You can see that it completely iterates if the condition does not match:
irb(main):007:0> a.each {|i| i.each {|j| p j; break if j == 999} or
break}
1
2
3
2
3
4
54
6
5
=> [[1, 2, 3], [2, 3, 4], [54, 6, 5]]
If we learn more about the problem that is to be solved here we may come
up
with even better solutions.
Cheers
robert