0
0
Rubyprogramming~5 mins

Loop method for infinite loops in Ruby

Choose your learning style9 modes available
Introduction

We use infinite loops to keep doing something over and over without stopping until we decide to stop it.

When you want a program to keep running until a user chooses to exit.
When waiting for an event or input that can happen anytime.
When creating a game loop that runs continuously.
When monitoring a system or sensor without interruption.
Syntax
Ruby
loop do
  # code to repeat
end

The loop do ... end runs the code inside forever unless you stop it.

You can use break inside the loop to stop it when needed.

Examples
This prints "Hello!" once and then stops the loop with break.
Ruby
loop do
  puts "Hello!"
  break
end
This prints numbers 1 to 3, then stops the loop.
Ruby
count = 1
loop do
  puts count
  count += 1
  break if count > 3
end
This keeps asking for input and repeats it until you type "exit".
Ruby
loop do
  input = gets.chomp
  break if input == "exit"
  puts "You typed: #{input}"
end
Sample Program

This program counts from 1 to 5 using an infinite loop and stops when count is greater than 5.

Ruby
count = 1
loop do
  puts "Count is #{count}"
  count += 1
  break if count > 5
end
OutputSuccess
Important Notes

Remember to always have a break condition inside an infinite loop to avoid freezing your program.

You can use next to skip to the next loop cycle without stopping.

Summary

The loop do ... end creates an infinite loop in Ruby.

Use break to stop the loop when needed.

Infinite loops are useful for repeating tasks until a condition is met.