0
0
RubyHow-ToBeginner · 3 min read

How to Use Loop Do in Ruby: Simple Guide with Examples

In Ruby, loop do creates an infinite loop that repeatedly runs the code inside its block until you explicitly stop it with break. It is useful for running code continuously or until a condition is met inside the loop.
📐

Syntax

The loop do syntax starts an infinite loop. The code inside the do...end block runs repeatedly. Use break inside the block to stop the loop when needed.

  • loop do: begins the loop
  • code block: the repeated code inside do...end
  • break: exits the loop
ruby
loop do
  # code to repeat
  break # stops the loop
end
💻

Example

This example prints numbers from 1 to 5 using loop do. It uses a counter variable and break to stop after 5.

ruby
count = 1
loop do
  puts count
  break if count >= 5
  count += 1
end
Output
1 2 3 4 5
⚠️

Common Pitfalls

A common mistake is forgetting to use break, which causes an infinite loop that never stops. Another is placing break incorrectly so the loop never ends or ends too early.

ruby
count = 1
loop do
  puts count
  count += 1
  # Missing break causes infinite loop
end

# Correct way:
count = 1
loop do
  puts count
  break if count > 5
  count += 1
end
📊

Quick Reference

Use loop do for infinite loops that you control with break. Remember to always include a break condition to avoid freezing your program.

KeywordPurpose
loop doStarts an infinite loop
breakExits the loop
do...endDefines the block of code to repeat

Key Takeaways

Use loop do to create an infinite loop in Ruby.
Always include a break statement inside the loop to stop it.
The code inside do...end runs repeatedly until break is called.
For counting or conditional loops, control the exit with a variable and break.
Forgetting break causes infinite loops that freeze your program.