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 ...
Get The Book of Ruby now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.