Often, you’ll want your computer to do the same thing over and over again. After all, that’s what they’re supposed to be good at doing.
When you tell your computer to keep repeating something, you also need to tell it when to stop. Computers never get bored, so if you don’t tell it when to stop, it won’t.
We make sure this doesn’t happen by telling the computer to repeat certain parts of a program while a certain condition is true. It works the way if works:
input = '' |
while input != 'bye' |
puts input |
input = gets.chomp |
end |
puts 'Come again soon!' |
<= |
|
=> | Hello? |
<= | Hello? |
=> | Hi! |
<= | Hi! |
=> | Very nice to meet you. |
<= | Very nice to meet you. |
=> | Oh...how sweet! |
<= | Oh...how sweet! |
=> | bye |
<= | Come again soon! |
It’s not a fabulous program, though. For one thing, while tests your condition at the top of the loop. In this case we had to tweak our loop so it could test there. This made us puts a blank line before we did our first gets. In my mind, it just feels like the gets comes first and the echoing puts comes later. It’d be nice if we could say something like this:
# THIS IS NOT A REAL PROGRAM! |
while just_like_go_forever |
input = gets.chomp |
puts input |
if input == 'bye' |
stop_looping |
end |
end |
|
puts 'Come again soon!' |
That’s not valid Ruby code, but it’s close! To get it to loop forever, we just need to give while a condition that’s always true. And Ruby does have a way to break out of a loop:
# THIS IS SO TOTALLY A REAL PROGRAM! |
while 'Spike' > 'Angel' |
input = gets.chomp |
puts input |
if input == 'bye' |
break |
end |
end |
|
puts 'Come again soon!' |
=> | Hi, and your name is... |
<= | Hi, and your name is... |
=> | Cute. And original. |
<= | Cute. And original. |
=> | What, are you like... my little brother?! |
<= | What, are you like... my little brother?! |
=> | bye |
<= | bye |
Come again soon! |
Now, isn’t that better? OK, I’ll admit, the 'Spike' > 'Angel' thing is a little silly. When I get bored coming up with jokes for these examples, I’ll usually just use the actual true object:
while true |
input = gets.chomp |
puts input |
if input == 'bye' |
break |
end |
end |
|
puts 'Come again soon!' |
=> | Hey. |
<= | Hey. |
=> | You again?! |
<= | You again?! |
=> | bye |
<= | bye |
Come again soon! |
And that’s a loop. It’s considerably trickier than a branch, so take a minute to look it over and let it sink in….
Loops are lovely things. However, like weapons-grade plutonium or bubble gum, they can cause big problems if handled improperly. Here’s a big one: what if your computer gets trapped in an infinite loop? If you think this may have happened, just go to your command line, hold down the Ctrl key, and press C. (You are running these from the command line, right?)
Before we start playing around with loops, though, let’s learn a few things to make our job easier.
18.117.233.26