Ruby Mini Project: Expense Report
Let's put the whole course together and build a small but complete program: an expense report generator. It reads raw expense lines (as you might export them from a banking app), validates them, groups and summarises them, and prints a neat report. Along the way you'll use strings, regex, hashes, Data, modules, Enumerable, exceptions, format and JSON.
We build it in five steps. Each step is a complete, runnable program that grows from the previous one.
The input
Our "file" is a heredoc with one expense per line: date, category, amount and description, separated by |. Some lines are broken on purpose — real data always is.
2025-03-01 | food | 12.40 | Lunch with team
2025-03-02 | transport | 2.80 | Bus ticket
2025-03-02 | food | 34.15 | Groceries
2025-03-03 | fun | 15.00 | Cinema
2025-03-04 | transport | abc | Taxi (amount missing)
2025-03-05 | food | 8.95 | Coffee and cake
2025-03-06 | rent | 650.00 | March rent
this line is garbageStep 1: parse lines into objects
We model one expense as an immutable Data object and parse each line with split and strip. For now we ignore validation.
RAW = <<~TEXT
2025-03-01 | food | 12.40 | Lunch with team
2025-03-02 | transport | 2.80 | Bus ticket
2025-03-02 | food | 34.15 | Groceries
TEXT
Expense = Data.define(:date, :category, :amount, :note)
def parse_line(line)
date, category, amount, note = line.split("|").map(&:strip)
Expense.new(date:, category: category.to_sym, amount: amount.to_f, note:)
end
expenses = RAW.lines.map { |line| parse_line(line) }
expenses.each { |e| p e }#<data Expense date="2025-03-01", category=:food, amount=12.4, note="Lunch with team">
#<data Expense date="2025-03-02", category=:transport, amount=2.8, note="Bus ticket">
#<data Expense date="2025-03-02", category=:food, amount=34.15, note="Groceries">
Categories become symbols because they are labels, not text for users.
Step 2: validate with exceptions
Bad lines should not crash the program — but they should not disappear silently either. We raise a custom ParseError with a helpful message, rescue it per line and collect the problems.
RAW = <<~TEXT
2025-03-01 | food | 12.40 | Lunch with team
2025-03-04 | transport | abc | Taxi (amount missing)
this line is garbage
2025-03-05 | food | 8.95 | Coffee and cake
TEXT
Expense = Data.define(:date, :category, :amount, :note)
class ParseError < StandardError; end
LINE_FORMAT = /\A\d{4}-\d{2}-\d{2}\s*\|/
def parse_line(line)
raise ParseError, "unrecognised format" unless line.match?(LINE_FORMAT)
date, category, amount, note = line.split("|").map(&:strip)
value = Float(amount, exception: false)
raise ParseError, "invalid amount #{amount.inspect}" if value.nil?
Expense.new(date:, category: category.to_sym, amount: value, note:)
end
expenses = []
errors = []
RAW.lines.each.with_index(1) do |line, number|
expenses << parse_line(line)
rescue ParseError => e
errors << "line #{number}: #{e.message}"
end
puts "#{expenses.size} valid expenses"
puts errors2 valid expenses
line 2: invalid amount "abc"
line 3: unrecognised format
Float(amount, exception: false) returns nil instead of raising for bad input — convenient for validation.
Step 3: summarise with Enumerable
Now the fun part: totals per category, the biggest expense, the daily average. All with Enumerable methods.
Expense = Data.define(:date, :category, :amount, :note)
expenses = [
Expense.new("2025-03-01", :food, 12.40, "Lunch with team"),
Expense.new("2025-03-02", :transport, 2.80, "Bus ticket"),
Expense.new("2025-03-02", :food, 34.15, "Groceries"),
Expense.new("2025-03-03", :fun, 15.00, "Cinema"),
Expense.new("2025-03-05", :food, 8.95, "Coffee and cake"),
Expense.new("2025-03-06", :rent, 650.00, "March rent"),
]
by_category = expenses
.group_by(&:category)
.transform_values { |list| list.sum(&:amount).round(2) }
.sort_by { |_, total| -total }
.to_h
p by_category
p expenses.sum(&:amount).round(2)
p expenses.max_by(&:amount).note
p expenses.map(&:date).uniq.size
p expenses.reject { |e| e.category == :rent }.sum(&:amount).round(2){rent: 650.0, food: 55.5, fun: 15.0, transport: 2.8}
723.3
"March rent"
5
73.3
Step 4: a reusable Report class
Let's wrap the logic in a class. It includes Enumerable (so a report is a collection of expenses), uses private helpers, and formats a text table with format.
Expense = Data.define(:date, :category, :amount, :note)
class Report
include Enumerable
def initialize(expenses) = @expenses = expenses
def each(&) = @expenses.each(&)
def total = sum(&:amount)
def by_category
group_by(&:category)
.transform_values { |list| list.sum(&:amount) }
.sort_by { |_, amount| -amount }
end
def to_text
lines = [header, rule]
by_category.each do |cat, amount|
lines << format("%-10s %9.2f %5.1f%% %s", cat, amount, share(amount), bar(amount))
end
lines << rule
lines << format("%-10s %9.2f", "TOTAL", total)
lines.join("\n")
end
private
def header = format("%-10s %9s %6s", "Category", "Amount", "Share")
def rule = "-" * 42
def share(amount) = amount / total * 100
def bar(amount) = "#" * (share(amount) / 10).ceil
end
report = Report.new([
Expense.new("2025-03-01", :food, 12.40, "Lunch with team"),
Expense.new("2025-03-02", :transport, 2.80, "Bus ticket"),
Expense.new("2025-03-02", :food, 34.15, "Groceries"),
Expense.new("2025-03-03", :fun, 15.00, "Cinema"),
Expense.new("2025-03-05", :food, 8.95, "Coffee and cake"),
Expense.new("2025-03-06", :rent, 650.00, "March rent"),
])
puts report.to_text
puts
puts "Food purchases: #{report.count { |e| e.category == :food }}"Category Amount Share
------------------------------------------
rent 650.00 89.9% #########
food 55.50 7.7% #
fun 15.00 2.1% #
transport 2.80 0.4% #
------------------------------------------
TOTAL 723.30
Food purchases: 3
def each(&) = @expenses.each(&) uses Ruby 3.1's anonymous block forwarding: the & simply passes the block along.
Step 5: the complete program
The final version combines everything: parsing with validation, the report, a budget check using pattern matching, and a JSON export for other tools.
require "json"
RAW = <<~TEXT
2025-03-01 | food | 12.40 | Lunch with team
2025-03-02 | transport | 2.80 | Bus ticket
2025-03-02 | food | 34.15 | Groceries
2025-03-03 | fun | 15.00 | Cinema
2025-03-04 | transport | abc | Taxi (amount missing)
2025-03-05 | food | 8.95 | Coffee and cake
2025-03-06 | rent | 650.00 | March rent
this line is garbage
TEXT
BUDGET = {food: 50, transport: 40, fun: 30, rent: 650}.freeze
Expense = Data.define(:date, :category, :amount, :note)
class ParseError < StandardError; end
module Parser
LINE_FORMAT = /\A\d{4}-\d{2}-\d{2}\s*\|/
module_function
def parse(text)
expenses, errors = [], []
text.lines.each.with_index(1) do |line, number|
expenses << parse_line(line)
rescue ParseError => e
errors << "line #{number}: #{e.message}"
end
[expenses, errors]
end
def parse_line(line)
raise ParseError, "unrecognised format" unless line.match?(LINE_FORMAT)
date, category, amount, note = line.split("|").map(&:strip)
value = Float(amount, exception: false) or raise ParseError, "invalid amount #{amount.inspect}"
Expense.new(date:, category: category.to_sym, amount: value, note:)
end
end
class Report
include Enumerable
def initialize(expenses) = @expenses = expenses
def each(&) = @expenses.each(&)
def total = sum(&:amount)
def by_category
group_by(&:category).transform_values { |list| list.sum(&:amount).round(2) }
end
def budget_status(budget)
by_category.map do |category, spent|
case [spent, budget[category]]
in [_, nil] then "#{category}: no budget set"
in [s, b] if s > b then format("%s: over budget by %.2f", category, s - b)
in [s, b] if s == b then "#{category}: exactly on budget"
in [s, b] then format("%s: %.2f left", category, b - s)
end
end
end
def to_h = {total: total.round(2), categories: by_category, count: count}
end
expenses, errors = Parser.parse(RAW)
report = Report.new(expenses)
puts "Parsed #{report.count} expenses (#{errors.size} skipped)"
errors.each { |e| puts " ! #{e}" }
puts
puts report.budget_status(BUDGET)
puts
puts JSON.generate(report.to_h)Parsed 6 expenses (2 skipped)
! line 5: invalid amount "abc"
! line 8: unrecognised format
food: over budget by 5.50
transport: 37.20 left
fun: 15.00 left
rent: exactly on budget
{"total":723.3,"categories":{"food":55.5,"transport":2.8,"fun":15.0,"rent":650.0},"count":6}
What you used
| Concept | Where |
|---|---|
Heredocs, split, strip |
reading the raw lines |
Regex match? |
rejecting garbage lines |
Custom exception + rescue in a block |
per-line validation |
Data.define |
immutable Expense records |
Modules with module_function |
the Parser namespace |
include Enumerable + each |
Report acts like a collection |
group_by, transform_values, sum, sort_by, max_by |
summaries |
format |
aligned table output |
| Pattern matching with guards | budget status |
JSON.generate |
export |
Ideas to extend it
- Read the expenses from a real file with
File.foreach(see File I/O). - Add a
--monthfilter usingDate.parseandselect. - Print the top three single expenses with
max_by(3, &:amount). - Write Minitest tests for
Parser.parse_linecovering valid lines, bad amounts and garbage. - Support several currencies with a conversion-rate hash and
RationalorBigDecimalfor exact arithmetic.
Tip: Notice how small each piece is. Good Ruby programs are built from many short methods with clear names, combined with Enumerable chains — exactly the style you have practised throughout this course.
Test yourself
Why is Expense defined with Data.define instead of Struct.new?
- Data is faster to parse
- Expenses should not change after parsing, and Data is immutable
- Struct cannot hold floats
- Data supports JSON automatically
What does Float("abc", exception: false) return?
- 0.0
- nil
- NaN
- It raises ArgumentError
Why can report.count and report.max_by be called on a Report?
- Report inherits from Array
- Report includes Enumerable and defines each
- Ruby adds them to every class
- They are defined with method_missing