loop do
In this page:
loop do
loop do ... end runs its block indefinitely, relying entirely on a break inside to stop -- Ruby's equivalent of an unconditional infinite loop. It's commonly used when the exit condition needs to be checked partway through the loop body. loop also automatically catches StopIteration, which makes it useful with enumerators.
Note: loop is the idiomatic choice when the stopping condition needs to be checked in the middle of the loop body, not just at the start.
Example: loop do
count = 1
loop do
puts "Count: #{count}"
count += 1
break if count > 3
end
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: