Skip to content

Instantly share code, notes, and snippets.

@warmwaffles
Last active December 23, 2015 04:59
Show Gist options
  • Save warmwaffles/6583767 to your computer and use it in GitHub Desktop.
Save warmwaffles/6583767 to your computer and use it in GitHub Desktop.
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
@warmwaffles
Copy link
Author

@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

@warmwaffles
Copy link
Author

I think a return [] would suffice

@lenards
Copy link

lenards commented Sep 16, 2013

Isn't return [] return an array and not an empty Range?

@percyhanna
Copy link

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.

@percyhanna
Copy link

Returning [] is also invalid because what if someone wants a Range, not an Array. Returning an empty array breaks the contract.

@lenards
Copy link

lenards commented Sep 16, 2013

I agree with Percy.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment