Peter Piper Peter Piper - 1 year ago 88
Ruby Question

Check if two ranges overlap in ruby

I know that I can do:

=> true

But when I try to do the same with another range it always returns false:

=> false

So my question is - is there any elegant way to compare two ranges in ruby? In my case I want to check if two DateTime-ranges overlap. Thanks in advance.

Answer Source

While the conversions may be wasteful, semantically comparing sets seems to make the most sense:
#=> true
#=> false

If you don't want to do that, you can do something like this (with r1 and r2 being ranges):

r1.cover?(r2.min) && r1.cover?(r2.max)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download