O'Reilly logo

Learning Sinatra by Manoj Sehrawat, Sudeep Agarwal

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Controlling the flow of iterations

It might sometimes be necessary to control the iterations in a loop structure for some conditions. Ruby provides three statements to control this flow:

  • break: This breaks the loop and comes out without executing any statements further
  • redo: This restarts the current iteration, skipping the execution of later statements
  • next: This starts the next iteration of the loop, skipping the execution of later statements
  • restart: This restarts the loop from the beginning

All these are generally used with conditions. Let's see an example:

for i in [1, 2, 3, 4, 5, 6 ]
  redo if i == 2
  next if i == 3
  break if i == 4
  retry if i == 5
  puts i
end

The preceding code shows the usage of all the four iteration controlling statements. Note ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required