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 the (i == arr.length) condition evaluates to true. Note that without a break, these would loop forever.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.224.226