Today I Learned

hashrocket A Hashrocket project

Ruby 2.6 introduces endless ranges `(1..)`

This syntax is basically a substitute for either (1..Float::INFINITY) or [1, 2, 3][1..-1].

One of the best use cases I've seen is from this April 2018 post:

case 2022
when(2030..)
  :mysterious_future
when(2020..)
  :twenties
when(2010..)
  :nowish
else
  :ancient_past
end
#=> :twenties

This reads a lot cleaner than it would with 2010...Float::INFINITY.

Another cool use is a short with_index using zip.

[1, 2, 3].zip(1..) { |a, index| puts "#{a}, #{index}"}
# 1 1
# 2 2
# 3 3

And additionally, you get a bit of safety that you didn't get with (1..Float::INFINITY):

(1..Float::INFINITY).to_a
# endless loop
(1..).to_a
# RangeError (cannot convert endless range to an array)

Which is a much better outcome for your program!

See More #ruby TILs
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.