O'Reilly logo

The Book of Ruby by Huw Collingbourne

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

loop

Unlike for and while, the loop command does not evaluate a test condition to determine whether to continue looping. To break out of the loop, you have to explicitly use the break keyword, as you can see in the following examples:

3loops.rb

i=0
loop do
    puts(arr[i])
    i+=1
    if (i == arr.length) then
       break
    end
end

loop {
    puts(arr[i])
    i+=1
    if (i == arr.length) then
       break
    end
}

These use the loop method repeatedly to execute the block of code that follows. These blocks are just like the iterator blocks you used earlier with the each method. Once again, you have a choice of block delimiters, either curly brackets or do and end.

In each case, the code iterates through the array, arr, by incrementing a counter variable, i, and breaking out of the loop when ...

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