← Back to Ruby Course | Chapter 6: Control Flow | Lesson 6 of 7

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:

  1. loop do
Syntax
ruby
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

markup
count = 1

loop do
  puts "Count: #{count}"
  count += 1
  break if count > 3
end
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
  1. Forgetting break, so loop do never ends.
  2. Putting break if count > 3 before the counter update, so it never stops or stops one step late.
  3. Using loop for a task with a known count, when times or each is clearer.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.