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

loop do

In this page:

  1. loop do

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
🔒

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.