Looping is one of the basic programming concepts that you will find in Ruby. It lets you to execute a block of code repeatedly. Ruby has a few ways to implement loops.
First up: `.while`.
The `.while` loop repeats a block of code over and over while the given condition remains true. When the condition becomes false, the loop ends.
Here is an example:
i = 0 # i starts off by equaling 0
while i < 5 # i is still 0 here so this is true
puts i # first time through the loop i equals 0
i += 1 # now i equals 1 and the loop starts again
end
# The output of this loop looks like:
# => 0
# => 1
# => 2
# => 3
# => 4
This is a rather simple loop so I will write it out another way to explain what is happening a bit.
## This code will output the same as the code above
i = 0
if i < 5 # Evaluates to true
puts i # Outputs 0
end
i += 1 # i is now 1
if i < 5 # Evaluates to true
puts i # Outputs 1
end
i += 1 # i is now 2
if i < 5 # Evaluates to true
puts i # Outputs 2
end
i += 1 # i is now 3
if i < 5 # Evaluates to true
puts i # Outputs 3
end
i += 1 # i is now 4
if i < 5 # Evaluates to true
puts i # Outputs 4
end
i += 1 # i is now 5
if i < 5 # Evaluates to false
puts i # Doesn't output anything
end
i += 1 # i is now 6
This very long set of if statements will `puts` the same thing as the much shorter loop. Please don’t write something like that long nonsense in professional code. It is just there to show you how much shorter you could write that code with a `.while` loop.
The second loop we will tackle is the `.until` loop. It is pretty much the exact opposite of the `.while` loop. The `.until` loop will run until the initial condition becomes true.
i = 0
until i == 5
puts i
i += 1
end
# => 0
# => 1
# => 2
# => 3
# => 4
This `.until` loop produces the same output as the `.while` loop up top (and as the unfortunate code that nobody should repeat in the middle). The choice between using the `.while` loop and the `.until` loop comes down the clarity and readability. You generally want to use `.while` if the condition is positive and `.until` if the condition is negative. For example:
while human.is_sick
rest_and_relax # Makes the human healthier
end
## This first conditional is pretty easy to
## understand.
until human.is_sick == false
rest_and_relax
end
## This second conditional is much more
## difficult to understand.
Those two loops are functionally the same thing but the first one is much more readable so we should prefer it.
That covers two basic loop types in Ruby. There are many more like `.for` and `.each` that I will cover another time.
Leave a Reply