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 |
<= ruby n00b still
@lenards Yes :D
Though I'm thinking about how to introduce a better return for the base case other than nil
because you can't do each on nil
I think a return []
would suffice
Isn't return []
return an array and not an empty Range?
Returning a Range
implies that there is a valid intersection of self
and other
. This is not true, there is no valid intersection.
I think the only reasonable cases would be to return nil
or raise a NoIntersection
exception or something.
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
Does the alias_method mean that you can do:
a & b #=> (2..3)
?