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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Returning
[]
is also invalid because what if someone wants aRange
, not anArray
. Returning an empty array breaks the contract.