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?
It's possible using DateTime::Infinity
class:
future = DateTime.now..DateTime::Infinity.new
future.include?(1_000_000.years.from_now) #=> true
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With