Main Content

Breaking a loop - Ruby and other languages

Archive - Originally posted on "The Horse's Mouth" - 2006-12-03 18:30:59 - Graham Ellis

When you're in a loop there are occasions you want to say get me our of this loop NOW, or "I'm done with the current iteration. And those are the 'classic' break and continue statements from C, C++ and Java. Languages like Perl changed break to last and continue to next ... and added a redo that asks for the current iteration to be rurun.

With me so far?

Now in Ruby ... you have break, you have next, you have redo and you also have retry ... which reenters the top of the loop. Wow - perhaps I had better provide an example?

for i in 1..5
print "How many do you need on day #{i}? "
nneed = gets.chomp.to_i
 
# next - don't order nothing; move on to next case
next if nneed == 0
 
# retry - whole thing to be redone on a 999 code
retry if [112,911,999].include?(nneed)
 
# redo - more than 10 ordered - must be a mistake
if nneed > 10 then print "Too many!\n"; redo; end
 
# break - code "-1" entered to exit on a short week
break if nneed == -1
 
print "We'll get #{nneed} on order for day #{i}\n"
end


By the way - if you've not seen much Ruby before, have a look through that example and taste a few of the constructs. It's really neat, and I expect I'll be writing a lot more about it in the future. ;-) . Source of this example [here].

New technical articles on Ruby:
How classes are defined and used
Ruby's Control statements
String functions in Ruby
Ruby Regular Expressions
Modules, Mixins and Comparators