From: "David A. Black" Date: 2008-08-07T08:00:32+09:00 Subject: Re: Need help detecting overlapping ranges Hi -- On Thu, 7 Aug 2008, Bryan Richardson wrote: > Hi David, > > I like the conciseness of your code, but I think it only works for when > the end of one range is the same as the beginning of another. I need to > also handle the times when ranges overlap more than that (i.e. 1..5, > 3..6 -> 1..6). Thanks for thinking about this! Here's the heavy artillery :-) def merge_ranges(ranges) ranges = ranges.sort_by {|r| r.first } *outages = ranges.shift ranges.each do |r| lastr = outages[-1] if lastr.last >= r.first - 1 outages[-1] = lastr.first..[r.last, lastr.last].max else outages.push(r) end end outages end require 'test/unit' class RangeTest < Test::Unit::TestCase def test_one ranges = [1..5, 20..20, 4..11, 40..45, 39..50] assert_equal([1..11, 20..20, 39..50], merge_ranges(ranges)) end def test_two ranges = [1..5, 7..11, 22..29, 5..8] assert_equal([1..11, 22..29], merge_ranges(ranges)) end def test_three ranges = [1..5, 7..11, 22..29, 6..8] assert_equal([1..11, 22..29], merge_ranges(ranges)) end end David -- Rails training from David A. Black and Ruby Power and Light: * Advancing With Rails August 18-21 Edison, NJ * Co-taught by D.A. Black and Erik Kastner See http://www.rubypal.com for details and updates!