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
class ToastBroadcaster include ActionView::RecordIdentifier def self.broadcast_to(user, message:, type: :notice)
How Turbo Stream toasts broadcast in Rails
turbo-streams
service-object
real-time
Intermediate
6 steps
ruby
class TemplateInterpolator PLACEHOLDER = /\{\{\s*([\w.]+)\s*\}\}/ def initialize(strict: false)
Interpolating templates with dotted keys in Ruby
regex
string-interpolation
hash-traversal
Intermediate
6 steps
ruby
class KeyTransformer def self.camelize(data) new.camelize(data) end
Recursively camelizing nested Ruby data
recursion
data-transformation
pattern-matching
Intermediate
7 steps
ruby
module Paginatable extend ActiveSupport::Concern private
A reusable pagination concern in Rails
pagination
concerns
http-headers
Intermediate
8 steps
ruby
class Api::MessagesController < ApiController before_action :authenticate_api_key! rate_limit to: 100,
Layered API rate limiting in Rails
rate-limiting
api-authentication
throttling
Intermediate
9 steps
ruby
class Order < ApplicationRecord include AASM belongs_to :warehouse
Modeling an order lifecycle with AASM in Rails
state machine
guards
callbacks
Intermediate
10 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.