If I have two ranges that overlap:
x = 1..10
y = 5..15
When I say:
puts x.include? y
the output is:
false
because the two ranges only overlap partially.
But if I want it to be "true" when there is partial overlap between two ranges, how would I write that? In other words I need a way to know when one range contains a subset of another range. I assume there's an elegant way to write this in Ruby but the only solutions I can think of are verbose.
Be careful using this with large ranges but this is an elegant way to do it:
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.
Some helpful enumerable methods:
If a range includes either the beginning or the end of a second range, then they overlap.
is the same as this:
This method can be used to test overlap between multiple ranges in an efficient way:
You can convert the ranges to an array, and use the
&
operator (conjunction). This returns a new array with all the elements occuring in both arrays. If the resulting array is not empty, that means, that there are some overlapping elements: