loop do
loop do runs its block over and over with no end until you say break. It is like a playground merry-go-round that runs until someone stops it.
In this page:
Syntax
loop do
# body
break if condition
end
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Forgetting
break, soloop donever ends. - Putting
break if count > 3before the counter update, so it never stops or stops one step late. - Using
loopfor a task with a known count, whentimesoreachis clearer.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: