ruby
35 lines · 9 steps
Building a pivot table in Ruby
Aggregate flat sales records into a region-by-quarter grid with row and column totals, then render it as tab-separated text.
Explained by
highlit
1def build_pivot_table(sales)
2 pivot = sales.each_with_object(Hash.new { |h, k| h[k] = Hash.new(0.0) }) do |record, table|
3 region = record.fetch(:region)
4 quarter = record.fetch(:quarter)
5 table[region][quarter] += record.fetch(:amount)
6 end
7
8 quarters = pivot.values.flat_map(&:keys).uniq.sort
9
10 rows = pivot.map do |region, by_quarter|
11 cells = quarters.map { |q| by_quarter[q] }
12 { region: region, cells: cells, total: cells.sum }
13 end
14
15 column_totals = quarters.each_with_index.map do |_, i|
16 rows.sum { |row| row[:cells][i] }
17 end
18
19 {
20 quarters: quarters,
21 rows: rows.sort_by { |row| -row[:total] },
22 column_totals: column_totals,
23 grand_total: column_totals.sum
24 }
25end
26
27def format_pivot(pivot)
28 header = ["Region", *pivot[:quarters], "Total"].join("\t")
29 body = pivot[:rows].map do |row|
30 [row[:region], *row[:cells].map { |c| format('%.2f', c) }, format('%.2f', row[:total])].join("\t")
31 end
32 footer = ["Total", *pivot[:column_totals].map { |c| format('%.2f', c) }, format('%.2f', pivot[:grand_total])].join("\t")
33
34 [header, *body, footer].join("\n")
35end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A Hash with a block default lets you accumulate into nested structures without pre-initializing keys.
- 2Deriving the column axis from the data keeps the table robust when records skip some quarters.
- 3Separating aggregation from formatting makes each stage independently testable and reusable.
Related explainers
ruby
class Order class InvalidTransition < StandardError; end TRANSITIONS = {
A state machine for order transitions in Ruby
state-machine
data-driven
error-handling
Intermediate
8 steps
ruby
class CreateOrderItems < ActiveRecord::Migration[7.1] def change create_table :order_items do |t| t.references :order, null: false, foreign_key: { on_delete: :cascade }
Enforcing order-item integrity in Rails
migrations
foreign-keys
validations
Intermediate
7 steps
ruby
class Registration < ApplicationRecord belongs_to :event validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP }
Validating registrations in Rails
validations
i18n
error-handling
Intermediate
8 steps
ruby
class ApacheLogParser LINE_PATTERN = /\A(?<ip>\S+)\s\S+\s\S+\s\[(?<time>[^\]]+)\]\s"(?<method>[A-Z]+)\s(?<path>\S+)\s(?<protocol>[^"]+)"\s(?<status>\d{3})\s(?<bytes>\d+|-)/ TIME_FORMAT = "%d/%b/%Y:%H:%M:%S %z"
Parsing Apache logs with named captures
regex
named-captures
parsing
Intermediate
6 steps
ruby
require "csv" def parse_transaction_row(line) fields = CSV.parse_line(line, headers: false, skip_blanks: true)
Parsing one CSV transaction row in Ruby
parsing
type-coercion
error-handling
Intermediate
6 steps
ruby
class NewCommentNotifier < ApplicationNotifier deliver_by :database deliver_by :email do |config|
Multi-channel notifications with Noticed in Rails
notifications
delivery-methods
fan-out
Intermediate
6 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/building-a-pivot-table-in-ruby-explained-ruby-5935/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.