Range#intersection method

I’ve had the need to find the “intersection” of 2 ranges, i.e. the maximal range that is wholly contained within those 2 ranges.

e.g. as a basic example:

(1..5).intersection(3..7) => (3..5) 

I was surprised that there is no such method on Range since it seems generally useful. There are some subtleties to defining it on Range itself since it’s unclear how it should work for “inverted” ranges (i.e. (5..1)) and returning nil when there’s no overlap doesn’t allow ranges to be “closed under intersection” since there’s no generic notion of an empty range.

I put up this PR with my implementation in case anyone has feedback or thinks it’s worth incorporating for others to leverage.

Curious what y’all think.

1 Like

I think typically the Rails team avoids merging in core extensions unless there is a relatively common case in practice, so I’m not sure if the best place for the PR at this moment is in Rails itself.

However, this sort of thing is related to some things I myself have found needed / useful, to the point where I put this up: GitHub - hernanat/extended_range: Adds some handy methods to the Ruby Range class

If your PR doesn’t find a home within Rails at this point in time, I would welcome it :slight_smile: