Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to express 'infinite time'?

Tags:

ruby

I am using the Range class to represent a range of times. Now I want a range which represents any point after a given time.

I tried (DateTime.now .. nil), but the Range class doesn't allow objects of different classes to be endpoints of the same range. (Attempting to create a Range with this property results in ArgumentError: bad value for range.)

Is there an equivalent of infinity for time, i.e. Time.now + (1.0/0.0)? Or alternately, is there a way to get around the Range class's requirement that its min and max values be of the same class?

like image 407
Ajedi32 Avatar asked Sep 24 '12 14:09

Ajedi32


3 Answers

It's possible using DateTime::Infinity class:

future = DateTime.now..DateTime::Infinity.new
future.include?(1_000_000.years.from_now) #=> true
like image 169
Tema Bolshakov Avatar answered Oct 05 '22 21:10

Tema Bolshakov


range = (Time.now.to_f .. Float::INFINITY)
range.include?(Time.now.to_f) # => true
sleep 1
range.include?(Time.now.to_f) # => true
range.include?(Float::INFINITY) # => true
like image 24
maerics Avatar answered Oct 05 '22 20:10

maerics


When you need to represent infinite time, you could use an object from a different class, that you create yourself. Just implement the matching operator and any other methods you use, and then it can be used interchangeably with Range objects.

class TimeRange
    def initialize(min, max)
    ...
    end
end
like image 26
David Grayson Avatar answered Oct 05 '22 19:10

David Grayson