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

Walkthrough

Space play step click any line
Three takeaways
  1. 1Memoizing an expensive parse step lets multiple report methods share one read of the source data.
  2. 2group_by plus transform_values is a clean idiom for building per-key aggregates from flat rows.
  3. 3Composing Enumerable methods like group_by, sum, and max_by expresses analytics without manual loops or mutable accumulators.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Aggregating CSV sales data in Ruby — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code