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 "net/http" require "json" require "uri" require "base64"
Paginating an HTTP API with a Ruby enumerator
pagination
http
enumerator
Intermediate
7 steps
ruby
module SlowQueryLogger SLOW_QUERY_THRESHOLD_MS = 200.0 IGNORED_PAYLOAD_NAMES = %w[SCHEMA TRANSACTION].freeze
Logging slow SQL queries in Rails
instrumentation
logging
pub-sub
Intermediate
7 steps
ruby
require "phonelib" class PhoneNumber class InvalidNumber < StandardError; end
Wrapping phone parsing in a Ruby value object
value-object
memoization
validation
Intermediate
7 steps
ruby
class PaymentGateway class MissingCredentialError < StandardError; end def initialize(env: Rails.env)
Wrapping Rails credentials in a gateway
encapsulation
credentials
error handling
Intermediate
6 steps
ruby
class WelcomeSequenceOrchestrator STEPS = [ { mailer: :welcome_email, delay: 0.hours }, { mailer: :getting_started, delay: 1.day },
Scheduling a drip email sequence in Rails
mailers
background jobs
scheduling
Intermediate
6 steps
php
function fuzzySearch(string $query, array $items, int $limit = 10): array { $query = mb_strtolower(trim($query));
Building a ranked fuzzy search in PHP
fuzzy-search
string-matching
ranking
Intermediate
7 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.