Ruby Range Intersection

August 29th, 2008

Here's an easy way to intersect two ranges in Ruby. The method will return a range for the range that is common (the overlap) between the two ranges; or nil if there is no overlap.
class Range
  def intersection(range)
    res = self.to_a & range.to_a
    res.empty? ? nil : (res.first..res.last) 
  end
  alias_method :&, :intersection
end

Sorry, comments are closed for this article.