July 4, 2018
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.
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 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.
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.
If this blog was helpful, check out our full blog archive.