Ruby: Loopy
A loop is a structure that allows us to run a block of code multiple times. Loops are helpful when we need to look at each element in an array or hash and modify them one by one. A basic loop in Ruby looks like:
A counter, often referred to as the index or i
, is important in a loop to indicate a point at which we want the loop to break, so that it does not run infinitely. If you accidentally create an infinite loop and run it on your terminal you can exit by inputting ctrl C
.
Times Loop
The Times Loop allows us to specify how many times we want it to run. It looks like this:
While Loop
The While Loop works on the condition that while something is true, it will commit to looping. It looks like this:
Until Loop
The Until Loop will loop until a certain condition is true. It looks like this:
For Loop
The For Loop looks at the position within a range of numbers and loops once for every position within it. It looks like this:
Iterating over Arrays
Sometimes we will want to loop through each element in an array and modify it. We can do this with the #each
method like so:
#each
takes each element of the array and runs it through the block, assigning it to x
(written between pipes) for purposes of manipulation. x
really stands for element, but you can write anything here to make it clear. Best would be number
, as each number
in the array of numbers
will print the boolen value as to whether it is even. Here is another example: