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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Hash.new(0) gives counters a zero default so you can increment keys without initializing them.
- 2each_with_object threads an accumulator through a collection, keeping the tallying logic in one expression.
- 3Normalizing timestamps to UTC and a fixed format makes grouping deterministic regardless of input type.
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 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
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
9 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/bucketing-log-entries-by-the-minute-in-ruby-explained-ruby-252b/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.