ruby 19 lines · 5 steps

Merging overlapping date ranges in Ruby

A sort-then-sweep pass collapses overlapping or adjacent ranges into a minimal set.

Explained by highlit
1class DateRangeMerger
2 def initialize(ranges)
3 @ranges = ranges
4 end
5 
6 def merge
7 sorted = @ranges.sort_by(&:begin)
8 
9 sorted.each_with_object([]) do |range, merged|
10 last = merged.last
11 
12 if last && range.begin <= (last.end + 1)
13 merged[-1] = (last.begin..[last.end, range.end].max)
14 else
15 merged << range
16 end
17 end
18 end
19end
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Sorting intervals by start turns overlap detection into a single left-to-right sweep.
  2. 2each_with_object threads an accumulator through iteration without a separate variable.
  3. 3Comparing against last.end + 1 merges adjacent ranges, not just strictly overlapping ones.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Merging overlapping date ranges in Ruby — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code