In the last Ruby article, we talked about how to store information in three different kinds of storages: variable, array, and a hash. After we get the data, we have many ways of using them, but, for right now,
we're going to only focus on loops
Loops
Ruby specializes in the concept of being able to do operations in many different ways. That is ever so true for loops. Let's get to it...
1) The "loop" loop
This kind of loop is called with a simple "loop {}" statement. It will continue to execute the block of code inside until it is told to stop. (This will be covered in the Error Handling article coming soon.)
2) Number iteration loop
A lot of times while I'm coding, I have a need to execute a block of code with a number then execute it again with the next number numerically. The number iteration loop makes this a breeze!
Note: The two periods in between the numbers means include the last number, while the three periods means include all numbers in between EXCEPT the last number.
3) "each do" loop
After we store data and we need to modify it, you would use the each do loop. For example, say we have an array of numbers and wanted to print the output of all the numbers times three. Your loop would look something like this:
Simplified down, this means, "For each item in number_array, store the value in V and then print the number multiplied by 3." Very simple right now, but it can get confusing fast. This can also be done with a hash. The only difference is you need two variables.
Loops are very important in coding. Now that you know about them, mess around with them or try to break them, but try to get comfortable with them, as they aren't going anywhere!
Next up: Basics of Ruby: Part 3 (operators and built-in functions)
Comments
No Comments Exist
Be the first, drop a comment!