Computers are dumb, but they're diligent. It's why I love them. Sure, I might have to be really precise when I give an instruction, but if I need that thing done 3000 times in a row, I'll be glad I told the computer exactly how. When I tell a computer to do something over and over, I'm working with loops. Ruby has several ways to loop, and each one is a little different. Let's discuss a few.
First, we have the condition-dependent while and until loops. While sets a condition and runs the loop as long as the condition is true. Until sets a condition and runs as long as that condition is false (i.e. *until* it is true, which is when the loop stops. While and until work well in situations where you don't want to move on without making sure a certaing thing gets done. You could run a game's turns through a while loop that ran as long as no player had won yet. Here's how we'd use while and until to count to ten:
The times loop is considerably less nuanced: It simply runs a block as many times as specified. You can run this loop with a number or by inserting a variable that corresponds to a number. This could be useful if you need to get something done a number of times, but that number depended on the result of another variable or calculation. Here's one way we could count to ten with times:
With the each loop, we get a little more versatility. Each can iterate across an array or hash and do the same thing to each item in it. Each loops as many times as there are items in the object being acted upon. When starting an each loop, you assign a variable name to stand in for each item worked with. This is great for sorting or reorganizing data. To illustrate, let's count to ten again:
Lastly, let's look at the for loop. For sets a range and then executes the loop for each item in that range. It's very straightforward and able to call on variables like the other loops. This might be good for running through data once of reach of a set of years, like (1985..2014). Let's see it in action for (1..10):
Just like with anything else in Ruby, the best way to get your mind around loops is to play with them in IRB and see what they can and can't do. Just remember that it is totally possible to write loops that never end (like a while loop with a condition that will neer be false), and you should press Ctrl - C if you get stuck in one of those to interrupt the program. Good luck, and happy coding!