Last active
December 23, 2015 04:59
-
-
Save warmwaffles/6583767 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Range | |
# Allows you to do the following | |
# | |
# a = (0..3) | |
# b = (2..4) | |
# a.intersection(b) #=> (2..3) | |
# | |
def intersection(other) | |
if self.max < other.begin || other.max < self.begin | |
return (1..0) | |
end | |
first = [self.begin, other.begin].max | |
last = [self.max, other.max].min | |
(first..last) | |
end | |
alias_method :&, :intersection | |
end |
Returning []
is also invalid because what if someone wants a Range
, not an Array
. Returning an empty array breaks the contract.
I agree with Percy.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Returning a
Range
implies that there is a valid intersection ofself
andother
. This is not true, there is no valid intersection.I think the only reasonable cases would be to return
nil
or raise aNoIntersection
exception or something.