This blog is part of our Ruby 2.6 series. Ruby 2.6.0-preview2 was recently released.

Before Ruby 2.6, if we want endless loop with index, we would need to use Float::INFINITY with upto or Range, or use Numeric#step.

Ruby 2.5.0
irb> (1..Float::INFINITY).each do |n|
irb*   # logic goes here
irb> end

OR

irb> 1.step.each do |n|
irb*   # logic goes here
irb> end

Ruby 2.6.0

Ruby 2.6 makes infinite loop more readable by changing mandatory second argument in range to optional. Internally, Ruby changes second argument to nil if second argument is not provided. So, both (0..) and (0..nil) are same in Ruby 2.6.

Using endless loop in Ruby 2.6
irb> (0..).each do |n|
irb*   # logic goes here
irb> end
irb> (0..nil).size
=> Infinity
irb> (0..).size
=> Infinity

In Ruby 2.5, nil is not an acceptable argument and (0..nil) would throw ArgumentError.

irb> (0..nil)
ArgumentError (bad value for range)

Here is the relevant commit and discussion for this change.

The Chinese version of this blog is available here.