Repeating code with loops
We have come to our next topic, which is loops. Ruby, just like other languages, has different ways of making the same code execute repeatedly. When we discussed arrays, specifically the array that contained instruments’ names, we saw an example of the for
loop, which was used to print each instrument contained in the array. But let’s look at another type of loop, one that is more commonly used: the while
loop.
The while
loop lets us repeat a code execution that is determined by a true/false condition. Let’s say we wanted to print a number from one to three. We could create a print
statement and simply repeat it three times while incrementing the value. However, let’s try a different way that will be more concise. Start by creating a counter
variable:
counter = 1
Now, we can start the while
loop cycle:
while counter <= 3 puts counter counter++ end
This may seem like valid code, but we will...