(Ruby) How do you check whether a range contains a subset of another range?
The efficient way is to compare the limits
(x.first <= y.last) and (y.first <= x.last)
If you're using Ruby 2.6, you can use Range#cover?
with another Range
.
(1..5).cover?(2..3) #=> true
(1..5).cover?(0..6) #=> false
(1..5).cover?(1...6) #=> true
You could also convert the ranges to sets, since you're basically doing set intersection here. Might be easier if you are dealing with more than two ranges.
x = (1..10).to_set
y = (5..15).to_set
!(x & y).empty? #returns true (true == overlap, false == no overlap)
Be careful using this with large ranges but this is an elegant way to do it:
(x.to_a & y.to_a).empty?