Peter Piper Peter Piper - 1 month ago 6
Ruby Question

Check if two ranges overlap in ruby

I know that I can do:

(1..30).cover?(2)
=> true


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

(1..30).cover?(2..3)
=> 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

While the conversions may be wasteful, semantically comparing sets seems to make the most sense:

Set.new(1..30).superset?(Set.new(2..3))
#=> true
Set.new(1..30).superset?(Set.new(0..3))
#=> 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)
Comments