Originally posted by Mark Herschberg: You can just put the rest of the code in a code block to mimic this behavior. Isn't that what Java does under the hood anyway with a break?
In this example <some code> will execute for every element, while <other code> will not. The point of a break in a loop (as opposed to continue) is that not only do you stop execution of the code for the current element, but you also stop the loop/each for all subsequent elements. So you would need the condition twice:
The duplicated condition check could be eliminated if the intended break occurs at the beginning or end of the code block.
To me, a break statement would look cleaner, and also avoid the need to repeatedly recheck the condition after the break had occurred. Usually this is not too big a deal, but for large collections the effect may be significant.
Venkat's example nicely avoids the repeated checks to to condition. However it is a bit less readable than might be desired, on first glance. And it's a bit more work to handle a break from the middle of the code:
For what it's worth, Ruby does allow break from within a closure, which terminates the controlling statement (e.g. each()). Meanwhile the BGGA proposal for closures in Java has very different consequences for break (as well as continue and return) which would not mesh well with this usage. [ April 09, 2008: Message edited by: Jim Yingst ]