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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Sorting intervals by start turns overlap detection into a single left-to-right sweep.
- 2each_with_object threads an accumulator through iteration without a separate variable.
- 3Comparing against last.end + 1 merges adjacent ranges, not just strictly overlapping ones.
Related explainers
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 steps
ruby
class ApplicationController < ActionController::Base EXPERIMENTS = { checkout_button_color: %w[control blue green], onboarding_flow: %w[control streamlined]
How A/B test cohorts are assigned in Rails
a-b-testing
cookies
hashing
Intermediate
8 steps
ruby
class SnippetHighlighter CONTEXT_RADIUS = 60 MAX_TERMS = 8
Building search-result snippets in Ruby
regular-expressions
text-processing
search
Intermediate
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/merging-overlapping-date-ranges-in-ruby-explained-ruby-1774/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.