Ruby Loops - Stop that Loop!
(Page 3 of 5 )
So now you have created a loop that won't quit. The loop models itself a regular Lindsey Lohan or Britney Spears and is clearly out of control. Partying all the time, forgetting articles of clothing, and forcing its utter untalents upon the world. Well, we're going to put a stop to the loopiness, quicker than an overnight stay at a celebrity rehab center.
There are three keywords you can use with loops. Want to see them in a table? Yeah, I thought you might:
Keyword | What it does |
Break | Ends the current loop it is in (if you have nested loops, it only ends the loop it is encapsulated with). |
Redo | Without checking the loop's criteria, it repeats the current loop. |
Next | Jumps to the next iterator or item. |
Let's break that infinite loop we created earlier:
loop do
puts “R U A DUMB PROGRAMMER?”
print “Enter YES to quit:”
gets
chomp
break if $_ == “YES” # if the user types YES, break the loop
end
The program will repeatedly ask the user if they are dumb for all eternity until they admit that YES, they are a dumb programmer.
Try, Try, Try Again
They always tell you if at first you don't succeed, try, try again. Well that's how I got my restraining order (knocks on door: Is Mrs. Jolie home? Knocks on door: Is Mrs. Jolie home? Kicks and screams as cops drag him away). Unlike the police and their stupid anti-stalking laws, Ruby allows you to keep trying by using the Retry statement. It forces a loop or iterator to completely start over.
Loop do
puts “Can you spell orange?:”
gets
chomp
retry if $_ != “orange” # remember != means does not equal
end
The above sample asks the user to spell the word orange. If they misspell it, the retry statement forces the loop to start again until they get it right.
Next: Reach Out and Touch Someone >>
More Ruby-on-Rails Articles
More By James Payne