'is it possible to create a date range in ruby from negative infinity

I'm struggling to define a date range in Ruby (2.6.3) that represents the range of dates up to a given date (in my examples it is Date.today):

BigDecimal("Infinity")...Date.today

*** ArgumentError Exception: bad value for range

nil...Date.today

*** ArgumentError Exception: bad value for range

Date::Infinity.new...Date.today

*** ArgumentError Exception: bad value for range

(Date.today...-Date::Infinity.new)

Fri, 31 May 2019...#

this one doesn't break, but also doesn't appear to give me a meaningful date range:

(Date.today...-Date::Infinity.new).include? Date.yesterday

false



Solution 1:[1]

Maybe not the best solution, but it can be helpful:

(-Float::INFINITY...Date.today.to_time.to_i).include? Date.yesterday.to_time.to_i
 => true

Solution 2:[2]

As of ruby 2.7, this is no longer an issue, infinite ranges are handled gracefully:

(..Date.today).cover?(100.years.ago)
=> true
(nil..Date.today).cover?(100.years.ago)
=> true

Solution 3:[3]

If you're interested in passing time ranges to ActiveRecord because you're using Ruby on Rails, Time.new(Float::MAX) and Time.new(-Float::MAX) are useful.

Here's an example:

def before(time)
  Time.new(-Float::MAX)..time
end

def after(time)
  time..Time.new(Float::MAX)
end

user.comments.where(created_at: before(user.subscribed_at))

Solution 4:[4]

Just to note, Ruby 2.6.x added (see comments) endless ranges, ..Date.today gives .cover?(other_date) == true for all Dates before today.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yurii Verbytskyi
Solution 2 Fred Willmore
Solution 3
Solution 4