Cover by Huw Collingbourne

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

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 ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required