After last week, I know you've been eagerly waiting for this, the fifth article in my Ruby on Rails series. This one will give you an in-depth look at Loops, Methods, and Blocks. Well maybe Blocks. You'll have to see. So without a bunch of unnecessary yammering, let's get to it.
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:
What it does
Ends the current loop it is in (if you have nested loops, it only ends the loop it is encapsulated with).
Without checking the loop's criteria, it repeats the current loop.
Jumps to the next iterator or item.
Let's break that infinite loop we created earlier:
puts “R U A DUMB PROGRAMMER?”
print “Enter YES to quit:”
break if $_ == “YES” # if the user types YES, break the loop
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.
puts “Can you spell orange?:”
retry if $_ != “orange” # remember != means does not equal
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.