|
Breaking a loop - Ruby and other languages
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. ;-)
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 (written 2006-12-03 18:30:59)
Associated topics are indexed under C203 - C and C based languages - Conditionals and LoopsH104 - PHP - Control StatementsP206 - Perl - More Loops and ConditionalsR104 - Ruby - Control Structures
Some other Articles
CSL, KISS and RTFMKISS - one action per statement please - PerlPractical polymorphism in actionGeorge Hotel and Well House Manor, MelkshamBreaking a loop - Ruby and other languagesProducts that our customers want more of1st, 2nd, 3rd revisited in RubyIt's the 1st, not the 1nd 1rd or 1th.Plain Ole nice picturesImproving the historic town of Melksham
|
2259 posts, page by page
Link to page ... 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, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46 at 50 posts per page
This is a page archived from The Horse's Mouth at
http://www.wellho.net/horse/ -
the diary and writings of Graham Ellis.
Every attempt was made to provide current information at the time the
page was written, but things do move forward in our business - new software
releases, price changes, new techniques. Please check back via
our main site for current courses,
prices, versions, etc - any mention of a price in "The Horse's Mouth"
cannot be taken as an offer to supply at that price.
Link to Ezine home page (for reading).
Link to Blogging home page (to add comments).
|
|