Loop do - Learn Ruby The Beginner Guide An Introduction to Ruby Programming (2015)

Learn Ruby The Beginner Guide An Introduction to Ruby Programming (2015)

Loop do

A code block in Ruby is a bit of code that contains instructions. We can use the loop method to iterate over a block of code like so:

loop {puts "I'm in a code block."}

I'm in a code block.

I'm in a code block.

I'm in a code block.

I'm in a code block.

...

..

.

This created an infinite loop. Not very useful.

Rather than using curly braces to contain our block of code, we can use the alternate do/end syntax.

We also don't want to be in an infinite loop. Let's use break to get out this loop when a certain condition is met.

x = 4

loop do

x -= 1

puts "In the loop!"

break if x == 0

end

In the loop!

In the loop!

In the loop!

In the loop!

Next

Consider the following for loop:

for num in 1..20

print num

end

1234567891011121314151617181920

We can skip over all the numbers that aren't multiples of three by using next.

for num in 1..20

next if num % 3 != 0

print num

end

369121518

Recall that modulo % returns the remainder of the numbers divided by whatever number we specify. Also, that != means not equal to.

5 % 3

2

Five was not printed out because it did not equal zero when we used modulo three on it. We went to the next number to check if it qualified. This process is repeated through each loop iteration.

Times

We can use the loop iterator .times to perform a task a specific number of times on each item in an object.

4.times {print "I doth repeat myself. "}

I doth repeat myself. I doth repeat myself. I doth repeat myself. I doth repeat myself.