In this post, we will have a look on various type of looping constructs in Ruby.

Let us check them one by one with examples:

1. While Loop

While loop executes till the condition is true.

Syntax

while condition do

end

Example:

i = 1
n = 5

while i <= 10  do
  puts("%d * %d = %d" % [i, n, i*n])
  i +=1
end
2. Begin While Loop

This loop executes its statements first and then checks the condition

Syntax

begin

end while condition

Example

n = 1
begin
  puts("n = %d" % n )
  n +=1
end while n%5!=0
3. For Loop

This loop executes till the loop counter variable is in the provided range. In the example below, i is the loop counter variable. The initial value of i is 1 and it the loop will execute till value of i is less than or equal to 10.

Syntax

for variable in range

end

Example

n = 5
for i in 1..10
  puts("%d * %d = %d" % [i, n, i*n])
end
4. Until Loop

This loop executes its code while condition is false.

Syntax

until condition do

end

Example

n = 5
until n < 1 do
  puts("n = %d" % n )
  n -=1
end
5. Begin Until Loop

This loop executes its statement first and then checks the condition. It runs till condition is false.

Syntax

begin

end until n < 1

Example

n = 5
begin
  puts("n = %d" % n )
  n -=1
end until n < 1
6. Each Loop

This loop executes its statement first and then checks the condition. It runs till condition is false.

Syntax

(range).each do |variable|

end

Example

n = 5
(1..10).each do |i|
   puts("%d * %d = %d" % [i, n, i*n])
end

Reverse order loop is a bit typical in Ruby. Here is an example:

n = 5
range = 10..1
(range.first).downto(range.last).each do |i|
  puts("%d * %d = %d" % [i, n, i*n])
end
Breaking the loop

We can stop the execution of a loop in the middle with the help of break statement. Here is an example:

n = 1
begin
  puts("n = %d" % n )
  n +=1

  if n>5 then
    break
  end

end while n%10!=0
Skipping loop statements

We can skip rest of the loop and jump to next iteration with the help of next. Here is an example:

n = 5
(1..10).each do |i|

  if i%2==0 then
    next
  end

  puts("%d * %d = %d" % [i, n, i*n])
  n -=1
end
Re-starting loop

We can reset a loop to start from beginning. Here is an example:

n = 1

while n <= 5

  for i in 1..10
    puts("%d * %d = %d" % [n, i, n*i])
  end

  puts("-----------------------")

  n += 1

  if n>5 then

    print("View again? y/n : ")

    choice = gets().strip()    #strip removes white space characters

    if choice == "y" then
      redo
    end
  end
end