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
@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