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

Viewed 1034

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

5 Answers

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

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

Why do you need infinity? How far back in time do you really need to go? Can't you just do something like this:

[*100.year.ago.to_date...Date.today]

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))

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

Related