Thuta Learning
Ruby
AdvancedProgrammingBeginner

Next Steps

RubyLesson 2945 min

What you'll walk away with

  • Recognise how the course's classes, modules, blocks, exceptions and JSON fit together in one program
  • Write your own collection class by defining each and including Enumerable
  • Write a program's own self-check with a lambda and a closure, without a test framework
  • Choose the track that matches your goal and start it with one small project

Explain it simply

Explain it simply

You have now met every basic piece of Ruby: variables, methods, arrays and hashes, blocks, classes and modules, exceptions, files, gems and tests. Owning the whole toolbox is like having all the knives and pans in a kitchen; you only learn how they work together by cooking a meal.

So the best next step is not one more tutorial but a small project of your own. This lesson shows what the shape of such a project looks like and points to the tracks you can follow afterwards.

Problem → Why → Solution

The problem: freezing in front of an empty file

A common trap after finishing a course is tutorial hopping. You can follow every example, yet you freeze in front of an empty file. The knowledge sits in separate boxes: one lesson for hashes, one for exceptions, one for JSON. A real feature needs all of them in one place and in the right order.

Without practice at joining them, code turns into one long script in which parsing, checking, adding up and printing are mixed together, like the one below. The cure is a small project where you have to decide for yourself where each responsibility lives.

tangled_import.rb
# Parsing, checking, adding up and printing tangled together
total = 0
File.readlines("expenses.csv").each do |line|    # Errno::ENOENT if the file is missing
  title, amount, category = line.split(",")
  next if amount.to_f <= 0                       # "n/a".to_f is 0.0: silently skipped
  total += amount.to_f                           # money as floats
  puts "#{title}: #{amount} (#{category})"       # category still has its newline
end
puts total

Why aren't separate lessons enough?

Each lesson shows one tool in isolation. What it cannot show are the seams between the tools: where raw input becomes a validated object, where an error is caught, where a result is calculated before it is printed. Choosing those seams is the main job of a project.

Core concept: one job per piece

The capstone below uses nearly everything in this course in one program, which makes it a good way to see how the pieces fit. An expense importer receives raw rows, like the strings you would get from a CSV file. Each row becomes a validated Expense object or is rejected with a reason. The accepted expenses are stored in a Ledger, summarised by a mixin, saved as JSON and loaded back, and finally the program checks its own results.

Notice the division of labour. Expense knows what a valid expense is and raises ValidationError when a row breaks the rules. Ledger only stores expenses and iterates over them; because it defines each and includes Enumerable, it gets map, group_by, sum and max_by for free. The Summarizable module adds domain knowledge (totals, totals per category) to any Enumerable that holds objects with cents and category. Each piece can be read, changed and tested without opening the others.

Two details are worth copying. Money is stored as integer cents, never as a float, so totals add up exactly. And the import loop rescues ValidationError per row, so one bad row cannot stop the whole import, while every rejection keeps its reason. The final self-check uses a lambda that counts passes in a variable it closes over, which ties back to the Procs, lambdas and closures lesson.

Course topicWhere it appears in the capstone
Classes and objectsExpense and Ledger
Modules and mixinsSummarizable included into Ledger
Blocks and iteratorsLedger#each, each_with_index, group_by, sum(&:cents)
Lambdas and closuresthe money formatter and the check lambda that counts passes
ExceptionsValidationError raised and rescued per row
Files and JSONsave and load inside Dir.mktmpdir
Mental model: raw rows in, report out
  1. Raw rows arrive as plain hashes
  2. Expense accepts or raises
  3. Ledger stores; Enumerable iterates
  4. A report and a self-check close the loop

Each piece does only its own job, so when the report looks wrong you know which piece to open.

General pattern

ruby
class Collection
  include Enumerable          # needs each; gives map, select, sum, max_by, ...

  def each(&block)
    return enum_for(:each) unless block   # no block given: return an Enumerator

    @items.each(&block)
    self
  end
end

A collection class of your own defines each and includes Enumerable, and gets map, select, sum and the rest automatically. Returning enum_for(:each) when there is no block keeps chains such as each_with_index working.

Capstone: an expense import and report

This single file contains every major part of the course. Eight prepared raw rows (four of them invalid) are turned into Expense objects, and the program prints totals per category and the biggest expense. Notice that money is kept as integer cents. Rejected rows are listed with their reasons, the valid ones are saved as JSON in a temp folder and loaded back, and the program finishes by printing how many self-checks passed.

capstone.rb
require "json"
require "tmpdir"

class ValidationError < StandardError; end

module Summarizable
  def total_cents = sum(&:cents)

  def totals_by_category
    group_by(&:category).transform_values { |expenses| expenses.sum(&:cents) }
  end
end

class Expense
  CATEGORIES = %w[food transport fun].freeze

  attr_reader :title, :cents, :category

  def self.from_row(row)
    new(
      title: row[:title].to_s,
      cents: (parse_amount(row[:amount]) * 100).round,
      category: row[:category].to_s.downcase
    )
  end

  def self.parse_amount(text)
    Float(text)
  rescue ArgumentError, TypeError
    raise ValidationError, "amount is not a number"
  end

  def initialize(title:, cents:, category:)
    raise ValidationError, "title is required" if title.strip.empty?
    raise ValidationError, "amount must be positive" unless cents.positive?
    unless CATEGORIES.include?(category)
      raise ValidationError, "unknown category '#{category}'"
    end

    @title = title.strip
    @cents = cents
    @category = category
  end

  def to_h = { title: title, cents: cents, category: category }
end

class Ledger
  include Enumerable
  include Summarizable

  def initialize(expenses = [])
    @expenses = expenses
  end

  def <<(expense)
    @expenses << expense
    self
  end

  def each(&block)
    return enum_for(:each) unless block

    @expenses.each(&block)
    self
  end

  def to_json_text = JSON.pretty_generate(map(&:to_h))

  def self.from_json_text(text)
    rows = JSON.parse(text, symbolize_names: true)
    new(rows.map { |attributes| Expense.new(**attributes) })
  end
end

def import(rows)
  ledger = Ledger.new
  rejected = []
  rows.each_with_index do |row, index|
    ledger << Expense.from_row(row)
  rescue ValidationError => error
    rejected << "row #{index + 1}: #{error.message}"
  end
  [ledger, rejected]
end

rows = [
  { title: "Lunch", amount: "4.50", category: "food" },
  { title: "Bus pass", amount: "30", category: "Transport" },
  { title: "Cinema", amount: "12.25", category: "fun" },
  { title: "Dinner", amount: "18.40", category: "food" },
  { title: "", amount: "5", category: "food" },
  { title: "Mystery", amount: "n/a", category: "fun" },
  { title: "Gift", amount: "20", category: "gifts" },
  { title: "Refund", amount: "-3", category: "food" }
]

ledger, rejected = import(rows)
money = ->(cents) { format("%.2f", cents / 100.0) }

puts "Imported #{ledger.count} of #{rows.size} rows"
ledger.totals_by_category.sort.each do |category, cents|
  puts "  #{category.ljust(10)} #{money.call(cents).rjust(7)}"
end
biggest = ledger.max_by(&:cents)
puts "Total: #{money.call(ledger.total_cents)} (largest: #{biggest.title})"
puts "Rejected:"
rejected.each { |reason| puts "  #{reason}" }

reloaded = nil
Dir.mktmpdir("ledger") do |dir|
  path = File.join(dir, "ledger.json")
  File.write(path, ledger.to_json_text)
  reloaded = Ledger.from_json_text(File.read(path))
end

checks = 0
check = lambda do |label, condition|
  raise "self-check failed: #{label}" unless condition

  checks += 1
end

bad_amount_raises = begin
  Expense.from_row(title: "x", amount: "abc", category: "fun")
  false
rescue ValidationError
  true
end

sums_match = ledger.totals_by_category.values.sum == ledger.total_cents
check.call("four rows imported", ledger.count == 4)
check.call("four rows rejected", rejected.size == 4)
check.call("categories add up to the total", sums_match)
check.call("JSON round trip keeps every row", reloaded.map(&:to_h) == ledger.map(&:to_h))
check.call("JSON round trip keeps the total", reloaded.total_cents == 6515)
check.call("a bad amount raises ValidationError", bad_amount_raises)
puts "#{checks} self-checks passed"

Code breakdown

  1. Mixindef total_cents = sum(&:cents)

    Summarizable does not know where sum comes from; it assumes it is mixed into a class that includes Enumerable. That is why Ledger needs both include Enumerable and include Summarizable.

  2. Validationraise ValidationError, "amount is not a number"

    parse_amount catches the generic ArgumentError from Float("n/a") and turns it into the domain's own ValidationError. The rescue sits in this one small method, so it cannot hide other bugs.

  3. Enumerableinclude Enumerable

    Ledger defines only each, yet count, map, max_by and group_by all work. ledger.count returns 4 and ledger.max_by(&:cents) picks Bus pass.

  4. Per-row rescuerescue ValidationError => error

    This rescue guards each pass of the each_with_index block, so an error in row 5 skips only row 5 and row 6 carries on. The reasons are collected in rejected.

  5. JSON loadnew(rows.map { |attributes| Expense.new(**attributes) })

    Each loaded row (a hash with symbol keys thanks to symbolize_names) is spread into keyword arguments with ** and passed to Expense.new again, so data coming from the file goes through the same validation.

  6. Closure countercheck = lambda do |label, condition|

    The check lambda holds the outer checks variable and adds 1 for every pass. When a check fails it raises, so the program stops at once and names the failing check.

You should see
Imported 4 of 8 rows
  food         22.90
  fun          12.25
  transport    30.00
Total: 65.15 (largest: Bus pass)
Rejected:
  row 5: title is required
  row 6: amount is not a number
  row 7: unknown category 'gifts'
  row 8: amount must be positive
6 self-checks passed

Four tracks to follow

There is no single road onwards. Choose your goal first: do you want to build websites, automate chores or understand the language more deeply? Start each track with one small project, and you can use this very capstone as the base.

TrackLearn nextFirst project
Language depthComparable, Struct and Data, pattern matching, lazy enumeratorsA text-statistics script using Data and case/in
Quality toolsMinitest or RSpec, RuboCop, Rake, BundlerAdd tests and a Rakefile to the capstone
The webRack, Sinatra, then RailsA tiny web page that lists the ledger
AutomationOptionParser, File and Dir, scheduled scriptsA command-line importer that takes a CSV path

A taste of three features to learn next

The script below shows three features this course left out but that you will meet constantly in modern Ruby code. Comparable gives you >, <, min and sort once you define <=>. case/in matches hashes and arrays against a pattern and pulls out the parts into variables. Data.define builds a small immutable value object in one line.

taste.rb
class Version
  include Comparable

  attr_reader :parts

  def initialize(text) = @parts = text.split(".").map(&:to_i)
  def <=>(other) = parts <=> other.parts
  def to_s = parts.join(".")
end

puts Version.new("1.10.0") > Version.new("1.9.9")          # true
puts [Version.new("2.0.0"), Version.new("1.4.2")].min      # 1.4.2

response = { status: "ok", items: [1, 2, 3] }
message = case response
          in { status: "ok", items: [first, *rest] }
            "first=#{first}, rest=#{rest}"
          in { status: "error" }
            "failed"
          end
puts message                                               # first=1, rest=[2, 3]

Coord = Data.define(:lat, :lng)
spot = Coord.new(lat: 16.8, lng: 96.2)
p spot                                # #<data Coord lat=16.8, lng=96.2>
p spot.with(lat: 17.0)                # #<data Coord lat=17.0, lng=96.2>
puts spot.frozen?                     # true

A habit for learning from here

1. Pick something you would really use

A problem from your own life, such as your expenses, a watch list or renaming files, keeps your motivation going far longer than an invented exercise.

2. Write a tiny script that works end to end

Before you split anything into layers, get a script of about fifty lines running from input to output.

3. Split into layers when it starts to hurt

When validation, storage and reporting are tangled and changes get hard, split them into classes and modules, as the capstone in this lesson does.

4. Test the logic layer

Cover the classes that have no I/O with Minitest, using the tools from the earlier lessons.

5. Read the source of a gem someone else wrote

Locate its files with gem which and read a small one. Comparing your style with someone else's is one of the fastest ways to learn.

In real projects

Where this shows up in real projects

The shape of this capstone shows up almost everywhere in professional Ruby code. In a Rails app, models hold validation and domain rules, ActiveRecord relations behave much like Enumerable and give you methods such as map and group_by, and Rake tasks run jobs like an import as commands. Well-known tools such as Homebrew and Jekyll are written in Ruby, so the source of tools you use every day can double as your textbook.

Most of the working day is spent reading and changing existing code rather than writing new code. That is why code with clearly separated pieces is so valuable to a team: when a bug turns up, you know which file to open. Recording rejected rows with their reasons, as this lesson does, matters in production too, because an error that carries a reason always beats data that silently disappears.

Common mistakes

Common mistakes

1. Tutorial hopping

Starting the next course the moment one ends feels like progress, but without code you wrote yourself the knowledge does not stick. When it gets hard, stay with your project instead of picking something new.

2. Jumping into Rails before the Ruby basics are solid

Rails leans heavily on Ruby's blocks, modules and metaprogramming, so with shaky basics its "magic" is just confusing. Make the basics of this course solid with a project first, then step in.

3. Skipping errors so data vanishes silently

If you write rescue => e and skip silently, nobody knows how many rows vanished after the import. Catch only ValidationError, as the capstone does, and record the reason, such as "row 6: amount is not a number".

4. Storing money as a Float

0.1 + 0.2 is 0.30000000000000004, and sums of floats cannot be trusted to match exactly. Store money as integers such as cents and convert only for display with format("%.2f", cents / 100.0).

Best practices

Best practices

  • Turn every new topic into a small project; for example, rewrite this lesson's capstone with your own data.
  • Give each class one job: a class for validation, a class for storage, a method for display.
  • Give every input that can go wrong a clear error class and a message that carries the reason.
  • Finish every piece of code with a self-check or a Minitest test of some kind.

Mini challenge

Mini challenge: a bookshelf importer

Rebuild the capstone's shape yourself, but with a bookshelf as the domain. Turn raw rows into Book objects, list the rejected ones with reasons, save as JSON and load it back.

  • Book validates title, pages and status (todo, reading, done) and raises BookError otherwise
  • A Statistics module provides total_pages and count_by_status and is included in a Shelf that is Enumerable
  • Convert each row with Integer(pages), rescue ArgumentError and BookError per row inside each_with_index, and list problems as "row 4: ..."
  • Save and reload JSON inside Dir.mktmpdir and print whether the data is the same
bookshelf.rb
require "json"
require "tmpdir"

# TODO: class BookError < StandardError

# TODO: module Statistics with total_pages and count_by_status (it relies on Enumerable)

# TODO: class Book: keyword arguments title:, pages:, status:; validate all three;
#       also a to_h that returns a hash with those keys

# TODO: class Shelf: include Enumerable and Statistics, define each, add a << method

rows = [
  ["Ruby Basics", "320", "reading"],
  ["Blocks in Depth", "180", "done"],
  ["Testing Notes", "240", "todo"],
  ["Mystery Novel", "many", "todo"],
  ["Someday Book", "200", "someday"]
]

# TODO: import the rows, collecting problems such as: row 4: invalid value for ...
# TODO: print the book count and pages, count per status, and the problems
# TODO: save as JSON in a temp folder, load it back and print whether the data matches

Expected: Nine lines are printed: 3 books, 740 pages done: 1 reading: 1 todo: 1 Problems: row 4: invalid value for Integer(): "many" row 5: unknown status 'someday' Reloaded: 3 books, 740 pages Same data: true

Show hint

A plain each that calls @books.each(&block) is enough, because Array already returns an enumerator when no block is given. When loading, pass symbolize_names: true and call Book.new(**attributes).

Show solution
bookshelf.rb
require "json"
require "tmpdir"

class BookError < StandardError; end

module Statistics
  def total_pages = sum(&:pages)

  def count_by_status = group_by(&:status).transform_values(&:count)
end

class Book
  STATUSES = %w[todo reading done].freeze

  attr_reader :title, :pages, :status

  def initialize(title:, pages:, status:)
    raise BookError, "title is required" if title.strip.empty?
    raise BookError, "pages must be positive" unless pages.positive?
    raise BookError, "unknown status '#{status}'" unless STATUSES.include?(status)

    @title = title.strip
    @pages = pages
    @status = status
  end

  def to_h = { title: title, pages: pages, status: status }
end

class Shelf
  include Enumerable
  include Statistics

  def initialize(books = [])
    @books = books
  end

  def <<(book)
    @books << book
    self
  end

  def each(&block) = @books.each(&block)
end

rows = [
  ["Ruby Basics", "320", "reading"],
  ["Blocks in Depth", "180", "done"],
  ["Testing Notes", "240", "todo"],
  ["Mystery Novel", "many", "todo"],
  ["Someday Book", "200", "someday"]
]

shelf = Shelf.new
problems = []
rows.each_with_index do |(title, pages, status), index|
  shelf << Book.new(title: title, pages: Integer(pages), status: status)
rescue ArgumentError, BookError => e
  problems << "row #{index + 1}: #{e.message}"
end

puts "#{shelf.count} books, #{shelf.total_pages} pages"
shelf.count_by_status.sort.each { |status, count| puts "  #{status}: #{count}" }
puts "Problems:"
problems.each { |problem| puts "  #{problem}" }

Dir.mktmpdir do |dir|
  path = File.join(dir, "shelf.json")
  File.write(path, JSON.generate(shelf.map(&:to_h)))
  saved = JSON.parse(File.read(path), symbolize_names: true)
  copy = Shelf.new(saved.map { |attributes| Book.new(**attributes) })
  puts "Reloaded: #{copy.count} books, #{copy.total_pages} pages"
  puts "Same data: #{copy.map(&:to_h) == shelf.map(&:to_h)}"
end

Quick quiz 1 / 3

At minimum, which method must a class define before it can include Enumerable?

Quick quiz 2 / 3

What does the capstone's import loop do with row 6 (amount "n/a")?

Quick quiz 3 / 3

Why does the capstone store money as integer cents?

What to remember

  • A project separates its layers (validation, storage, report), and each does one job.
  • Define each and include Enumerable and your own collection gets map, group_by and sum, while a mixin module adds domain logic.
  • Rescue only your own error class per row and record the reason, so data never disappears silently; store money as integer cents.
  • Pick one track (language depth, tooling, web, automation) and start it with one small project.

Ruby 4.0 Release — Ruby

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Next Steps | Thuta Learning