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
module DurationFormatter UNITS = [ ['week', 604_800], ['day', 86_400],
Turning seconds into human-readable durations in Ruby
greedy-decomposition
modular-arithmetic
formatting
Intermediate
7 steps
ruby
class Comment < ApplicationRecord belongs_to :post belongs_to :author, class_name: "User"
Live-updating comments with Turbo in Rails
turbo-streams
callbacks
associations
Intermediate
8 steps
ruby
require 'json' require 'set' class SensitiveScrubber
Recursively scrubbing secrets from JSON
recursion
data-masking
pattern-matching
Intermediate
7 steps
rust
use std::collections::HashMap; pub struct Memoizer<K, V, F> { cache: HashMap<K, V>,
A generic memoizer in Rust
memoization
generics
caching
Intermediate
6 steps
ruby
class ReportBatcher BATCH_SIZE = 500 def initialize(account)
Batching monthly email summaries in Rails
batching
service-object
background-jobs
Intermediate
7 steps
ruby
class Comment < ApplicationRecord belongs_to :commentable, polymorphic: true, counter_cache: true belongs_to :author, class_name: "User"
How polymorphic comments work in Rails
polymorphic-association
concerns
counter-cache
Intermediate
8 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.