Ruby Loops
Loops are used to execute the same block of code a certain number of times. This post details main the loop statements used in Ruby.
How do we build a loop, that executes exactly 5 times?
In the first step, we need to set a counter.
counter = 0 # It starts our counter at 0
Then we increment our counter by 1 and set it equal to the sum of its current value, plus 1
loop do
counter = counter + 1
Put the code to be executed
puts "I love Ruby #{counter}!"
In the last step, we should conditionally break out of the loop when the counter reaches 5.
if counter >= 5 # If our counter is 5 or more
break # Stop the loop
end
end
Final code
counter = 0loop do
counter = counter + 1
puts "I love Ruby #{counter}!"
if counter >= 5
break
end
end
If you paste this to IRB it will print out:
I love Ruby 1!
I love Ruby 2!
I love Ruby 3!
I love Ruby 4!
I love Ruby 5!
TIMES METHOD LOOP
The “times” method is called on an Integer (5
or 99
) and executes the block a certain number of times (the number that it's called on).
Please the example below:
4.times doputs "I am time method"end--------
Irb output -
"I am times method"
"I am times method"
"I am times method"
"I am times method"
“while” loop
As its name suggests the while
will keep executing a block as long as a specific condition is met or true
.
Let’s look at an example below
num_of_beers_drinked = 0
# => 0 (return value)
while num_of_beers_drinked < 4
num_of_beers_drinked += 1
puts "I have now drinked #{num_of_beers_drinked} beer(s)."
end
# => nil (return value)
puts "You drunk a total of #{num_of_beers_drinked} beers!"
# => nil (return value)Output:# > "I have now drinked 1 beer(s)."
# > "I have now drinked 2 beer(s)."
# > "I have now drinked 3 beer(s)."
# > "I have now drinked 4 beer(s)."
# > "You drunk a total of 4 beers!"
“UNTIL” loop
until
is simply the opposite of a while
loop. The block of code following until
will execute while the condition is false.
See the example below:
def party num_of_beers_drinked = 0 until num_of_beers_drinked == 4 puts 'You are good boy' num_of_beers_drinked += 1 endend
when we invoke the “party” function it returns:
'You are good boy''You are good boy''You are good boy''You are good boy'