ruby
32 lines · 7 steps
Rolling averages with each_cons in Ruby
A MetricSeries turns a stream of readings into windowed averages, smoothed points, and anomaly detection.
Explained by
highlit
1class MetricSeries
2 def initialize(readings, window: 5)
3 @readings = readings
4 @window = window
5 end
6
7 def rolling_averages
8 return [] if @readings.size < @window
9
10 @readings.each_cons(@window).map do |slice|
11 slice.sum.fdiv(@window).round(2)
12 end
13 end
14
15 def smoothed_points(timestamps)
16 offset = @window - 1
17 labels = timestamps.drop(offset)
18
19 labels.zip(rolling_averages).map do |at, value|
20 { at: at, value: value }
21 end
22 end
23
24 def anomalies(threshold:)
25 baseline = rolling_averages
26
27 @readings.drop(@window - 1).zip(baseline).filter_map do |actual, avg|
28 deviation = (actual - avg).abs
29 { actual: actual, expected: avg, deviation: deviation.round(2) } if deviation > threshold
30 end
31 end
32end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1`each_cons` gives you overlapping sliding windows without any manual index bookkeeping.
- 2Aligning derived series with their source requires dropping the leading `window - 1` elements the window consumes.
- 3`filter_map` combines transformation and selection in one pass, keeping only the results that matter.
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/rolling-averages-with-each_cons-in-ruby-explained-ruby-88db/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.