July 2011
Intermediate to advanced
400 pages
8h 46m
English
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 ...
Read now
Unlock full access