Ruby loop do

The loop do is a basic way to repeat a block of code multiple times. This loop runs forever, unless you tell it to stop with the break statement.

Here's a quick example of loop do. You can read the rest of the tutorial to learn more.

Example

counter = 1

loop do
  puts "Counter: #{counter}"
  counter += 1

  # Terminate loop if counter > 2
  break if counter > 2
end

# Output:
# Counter: 1
# Counter: 2

Here, the counter variable is initialized to 1. Then, the loop runs and prints the counter value. It continues running until counter is greater than 2.


Ruby loop do Syntax

The syntax of Ruby loop do is:

loop do
  # Code to run
end

As mentioned before, this loop will run forever unless you use break to exit the loop.


Example 1: Infinite Loop

Let's see what happens when we don't use a break statement to terminate the loop:

# Infinite loop
loop do
  puts "This will print forever!"
end

Output

This will print forever!
This will print forever!
This will print forever!
This will print forever!
... ... ...

This loop prints the message forever. A loop that runs forever is known as an infinite loop.

To stop the loop, you must interrupt the program.

Note: You can stop an infinite loop by pressing Ctrl + C in your terminal. This sends an interrupt signal to halt the program.


Example 2: Loop with break

Next, let's see how we can stop the infinite loop using the break statement:

counter = 1

loop do
  puts "This will print forever!"
  counter += 1
  
  # Terminate the loop if counter > 3
  break if counter > 3
end

Output

This will print forever!
This will print forever!
This will print forever!

Here, the loop runs until counter becomes greater than 3. The break statement is what stops the loop:

break if counter > 3

Example 3: Skipping Certain Iterations

The next statement skips the rest of the current loop iteration and starts the next one. For example,

i = 0

loop do
  i += 1
  next if i == 2
  puts i
  break if i >= 3
end

Output

1
3

When i == 2, Ruby skips the iteration (puts i is not executed) and goes to the next loop cycle.


Example 4: Simulating a do...while Loop

Ruby doesn't have a built-in do...while loop like some other languages, but you can use loop do...end to simulate it.

Note: A do...while loop runs the code at least once before checking the condition. Thus, the code inside the loop will be executed at least once, even if the condition is already false.

Example

num = 0

loop do

  # Print the value of num
  puts "Number is #{num}"

  # Increase the value of num
  num += 1

  # Terminate the loop if num is less than 3
  break if num < 3
end

Output

Number is 0

Even though num is already less than 3 at the start, the loop still prints it before checking the condition.

This happens because the break statement comes after the main code inside the loop.

So, the loop body always runs at least once, even if the condition to stop it is already true.

Note: Ruby also provides the begin...end while loop, which is similar to a do...while loop. However, this loop is discouraged by many Ruby developers because it can reduce readability and make code harder to maintain.


Frequently Asked Question

Is the begin...end while loop similar to a do...while loop?

The Ruby begin...end while loop is similar to a do...while loop in other languages.

In this loop, the code is executed at least once before the condition is checked. Its syntax is:

begin
  # Code to execute
end while condition

Here, the begin loop first executes the code, and only then checks the condition:

  • If the condition is true, the loop runs again.
  • If the condition is false, the loop ends.

Example

num = 0

begin
  puts "Number is #{num}"
  num += 1
end while num > 3

Output

Number is 0

Here, the loop will run as long as num is greater than 3. However, num is initially 0 (less than 3), so the condition num > 3 is false.

But the begin loop runs once and prints Number is 0 before terminating.

As you can see, this loop acts just like a do...while loop, i.e., the first iteration always happens regardless of whether the condition is true or false.

Note: The begin...end while loop is discouraged by many Ruby developers because it can reduce readability and make code harder to maintain. Instead, they prefer loop do...end with a break statement, which is clearer and more flexible.


Example 5: Get User Input Until the User Enters a Negative Number

Let's mimic a do...while loop that will keep on taking numbers from the user until they enter a negative number (the loop gets terminated).

Outside the loop, we'll print the sum of the entered numbers (excluding the negative number):

sum = 0

loop do
  print "Enter a number: "
    
  # Get user input and convert it to integer
  num = gets.chomp.to_i
    
  # Terminate the loop if num is negative
  break if num < 0
    
  # Else, add num to sum
  sum += num
end

puts "Sum = #{sum}"

Output

Enter a number: 25
Enter a number: 36
Enter a number: 0
Enter a number: 13
Enter a number: -9
Sum = 74

Here, the loop will execute as long as the user input num is not a negative number. If num is

  • Negative: The loop is terminated.
  • Not Negative: The value of num is added to sum.

Once the loop terminates, we print the sum variable, which is the sum of all non-negative numbers the user has entered so far.

Tip: If you're using loop do for input validation or retrying an operation, always ensure there's a clear break condition to avoid accidental infinite loops.

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges