This blog is part of our Ruby 2.6 series.
Before Ruby 2.6, if we want endless loop with index, we would need to use Float::INFINITY with up to or Range, or use Numeric#step.
Ruby 2.5.0
1irb> (1..Float::INFINITY).each do |n| 2irb\* # logic goes here 3irb> end
OR
1irb> 1.step.each do |n| 2irb\* # logic goes here 3irb> 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
1irb> (0..).each do |n| 2irb\* # logic goes here 3irb> end
1irb> (0..nil).size 2=> Infinity 3irb> (0..).size 4=> Infinity
In Ruby 2.5, nil is not an acceptable argument and (0..nil) would throw ArgumentError.
1irb> (0..nil) 2ArgumentError (bad value for range)
Here is the relevant commit and discussion for this change.
The Chinese version of this blog is available here.