ruby
34 lines · 6 steps
Aggregating CSV sales data in Ruby
A SalesReport class groups parsed CSV rows by region, then derives revenue and top sales reps from those groups.
Explained by
highlit
1require "csv"
2
3class SalesReport
4 def initialize(path)
5 @path = path
6 end
7
8 def by_region
9 rows.group_by { |row| row["region"] }
10 end
11
12 def revenue_by_region
13 by_region.transform_values do |group|
14 group.sum { |row| row.fetch("amount").to_f }
15 end
16 end
17
18 def top_rep_per_region
19 by_region.transform_values do |group|
20 group
21 .group_by { |row| row["rep"] }
22 .max_by { |_rep, sales| sales.sum { |s| s["amount"].to_f } }
23 .first
24 end
25 end
26
27 private
28
29 def rows
30 @rows ||= CSV.read(@path, headers: true, converters: nil).map do |row|
31 row.to_h.transform_keys(&:strip)
32 end
33 end
34end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Memoizing an expensive parse step lets multiple report methods share one read of the source data.
- 2group_by plus transform_values is a clean idiom for building per-key aggregates from flat rows.
- 3Composing Enumerable methods like group_by, sum, and max_by expresses analytics without manual loops or mutable accumulators.
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/aggregating-csv-sales-data-in-ruby-explained-ruby-3039/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.