ruby 28 lines · 5 steps

Bucketing log entries by the minute in Ruby

A small class groups timestamped log entries into per-minute counts and surfaces the busiest windows.

Explained by highlit
1class LogAggregator
2 BUCKET_FORMAT = "%Y-%m-%dT%H:%M"
3 
4 def initialize(entries)
5 @entries = entries
6 end
7 
8 def per_minute_counts
9 @entries.each_with_object(Hash.new(0)) do |entry, buckets|
10 key = bucket_key(entry.fetch(:timestamp))
11 buckets[key] += 1
12 end
13 end
14 
15 def busiest_minutes(limit = 5)
16 per_minute_counts
17 .sort_by { |_bucket, count| -count }
18 .first(limit)
19 .to_h
20 end
21 
22 private
23 
24 def bucket_key(timestamp)
25 time = timestamp.is_a?(Time) ? timestamp : Time.parse(timestamp)
26 time.utc.strftime(BUCKET_FORMAT)
27 end
28end
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Hash.new(0) gives counters a zero default so you can increment keys without initializing them.
  2. 2each_with_object threads an accumulator through a collection, keeping the tallying logic in one expression.
  3. 3Normalizing timestamps to UTC and a fixed format makes grouping deterministic regardless of input type.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Bucketing log entries by the minute in Ruby — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code