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
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/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.