A Ruby infinite loop is one of the most dreaded errors when coding in Ruby because the code inside the loop will just run forever. This can be dangerous if there is a lot of code inside the loop, as it will use a ton of your computer’s resources and usually cause a crash.

Here are two examples of an infinite loop in Ruby. One in a do loop and one in a while loop.

i = 1
loop do
  puts i
  break if i < 1
  i += 1
  #This code will never stop
end
i = 1
while  i > 0 
  #The code inside this while loop will never stop
  puts i
  i += 1
end

In the do loop above, the code will generate an infinite loop because the variable i is set to the number 1 to start. You then have the natural progression of increasing the value of the number until it reaches a condition that will not be true, our break condition that will stop the loop. However, in the code above, that condition is that i < 1. Since i (which is 1) is equal to 1, we add 1 to it and try again. We get 2 < 1, which is false. We then repeat the step until, well forever. Because we are adding 1 each time, the condition i < 1 will never be true, and so the loop will never break and run forever.

The second example is basically the same as the do loop. The while condition of i > 0 will always be true and so the code inside the while loop will run forever.

Let's take a look at one of these in action.

Ruby Infinite Loop in Action, Kind Of

In this example, we will run an infinite loop, well kind of. Because we don't want to crash your computer, we will show the start of an infinite loop, and add some safety code to make sure you always avoid infinite loops.

The Ruby code for this example will be pretty simple. We will run the while infinite loop example from above with some code in it. We will print some code so you can see how many times the code will run.

Like we said at the start, since we don't want to do any damage, we will put a safety check in place. We will not let this code run more than 1000 times. We can set this number to some number we know should not be reached if the code runs correctly. So we will add some code into the while loop and add a conditional check to make sure we avoid the infinite loop.

Here is the Ruby code:

i = 1
infinite_loop_safety_check = 0
  while( i > 0 && infiniteLoopSafetyCheck < 1000 ){
    puts i
    i+= 1
    infiniteLoopSafetyCheck += 1
  end

#Output
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
...
1000

Hopefully this article has been useful for you to understand the Ruby infinite loop.

Categorized in:

Ruby,

Last Update: March 11, 2024