From scripts to software
So far every program has been a single file using only what comes with Ruby. Real projects depend on libraries written by others, are worked on by several people, must keep working as they change, and are deployed to servers. The Ruby community has a well-established toolkit for all of this, much of it invented or popularised by Ruby before other languages adopted the same ideas:
- RubyGems packages and distributes libraries ("gems"), and Bundler gives each project an exact, reproducible set of them.
- Minitest (shipped with Ruby) and RSpec run automated tests, and testing is a deep part of Ruby culture.
- RuboCop keeps code consistent; the debug gem helps you look inside a running program; RBS and friends add optional type checking.
- Ruby on Rails combines all of these into a framework for web applications.
This lesson walks through each and then puts the whole course together in a complete small program with its own tests.
RubyGems and Bundler
A gem is a packaged Ruby library with a name, a version, its code and a description of its own dependencies (its .gemspec). Gems are published on RubyGems.org. gem install nokogiri installs one globally, and require "nokogiri" loads it. Ruby itself comes with many gems: default gems are part of Ruby and always available, while bundled gems are installed with Ruby but versioned separately. Over recent releases several libraries moved from default to bundled (for example csv, base64 and bigdecimal in Ruby 3.4), which matters because a project that uses Bundler must then list them in its Gemfile.
Bundler manages a project's gems. You declare what you need in a Gemfile:
source "https://rubygems.org"
gem "nokogiri", "~> 1.16" # parse HTML and XML
gem "csv" # a bundled gem: list it explicitly
group :development, :test do
gem "debug"
gem "rubocop", require: false
end
group :test do
gem "minitest"
endbundle install # resolve versions, install them, write Gemfile.lock
bundle add faraday # add a gem to the Gemfile and install it
bundle exec rake test # run a command with exactly the locked gems
bundle outdated # list gems with newer versions available
bundle update faraday # move one gem to the newest version the Gemfile allowsDefinition— The pessimistic operator
"~> 1.16" means "at least 1.16, but below 2.0"; "~> 1.16.2" means "at least 1.16.2, below 1.17". It allows the updates that semantic versioning promises are compatible and blocks the rest.
Definition— Gemfile.lock
The exact version of every gem the project uses, including dependencies of dependencies, written by Bundler. Applications commit it so every developer, the CI server and production run identical code. bundle exec (or require "bundler/setup") makes Ruby load exactly those versions.
Rake, Ruby's build tool, runs tasks defined in a Rakefile (rake test, rake db:migrate); it ships with Ruby as a bundled gem.
Testing with Minitest
Ruby developers write a lot of tests: in many Ruby teams, a change without tests is not considered finished. Minitest comes with Ruby (as a bundled gem), is small and fast, and is what Rails uses by default. It offers two styles, which you can mix:
# frozen_string_literal: true
require "minitest"
require "minitest/spec"
module Slug
def self.from(title)
title.downcase.gsub(/[^a-z0-9]+/, "-").delete_prefix("-").delete_suffix("-")
end
end
# Classic style: a class per subject, a method per test, assertions inside.
class SlugTest < Minitest::Test
def test_lowercases_and_joins_words
assert_equal "hello-kampala", Slug.from("Hello, Kampala!")
end
def test_collapses_runs_of_punctuation
assert_equal "a-b", Slug.from("a -- ... b")
end
def test_unicode_letters_are_dropped_for_now
skip "decide how to transliterate letters such as ã and ø"
end
end
# Spec style: describe and it blocks, with expectations.
describe Slug do
it "returns an empty slug for punctuation only" do
_(Slug.from("?!")).must_be_empty
end
it "never starts or ends with a dash" do
_(Slug.from(" spaces ")).must_equal "spaces"
end
end
exit Minitest.run(%w[--seed 42])Run options: --seed 42
# Running:
....S
Finished in 0.001385s, 3609.1598 runs/s, 3609.1598 assertions/s.
5 runs, 5 assertions, 0 failures, 0 errors, 1 skips
You have skipped tests. Run with --verbose for details.In the classic style, a test is a class inheriting from Minitest::Test, and every method whose name starts with test_ is a test. Assertions put the expected value first: assert_equal expected, actual. Others include assert, refute, assert_nil, assert_includes, assert_in_delta (for floats), assert_match (for regular expressions) and assert_raises, which returns the exception so you can check its message. skip marks a test as pending.
In the spec style (after require "minitest/spec"), describe and it blocks name the behaviour, and expectations read left to right: _(value).must_equal expected.
The output is worth reading: one character per test (. passed, F failed, E raised an error, S skipped), then a summary. Minitest runs tests in a random order, chosen by the seed it prints, so that tests which secretly depend on each other are caught; rerun with the same --seed to reproduce an order-dependent failure. The seed is fixed here so the order is repeatable, but the timing line differs on every run. In a project, tests live in test/ (one file per class, such as test/slug_test.rb), usually start with require "minitest/autorun", which runs them when the file ends, and are run with rake test or bin/rails test.
Minitest 6, the version bundled with Ruby 4.0, no longer includes minitest/mock (requiring it raised a LoadError when we tried). Many teams prefer simple hand-written fake objects anyway, passed in through constructors as the lesson on classes recommended.
RSpec is the other major testing framework, popular in many Rails teams. Its syntax is built on blocks and is meant to read like a specification:
RSpec.describe Slug do
it "joins words with dashes" do
expect(Slug.from("Hello, Kampala!")).to eq("hello-kampala")
end
context "with only punctuation" do
it { expect(Slug.from("?!")).to be_empty }
end
end(RSpec is a separate gem, so this fragment is not run by this course's tests.) Choose whichever your team uses; the habits matter more than the tool: test behaviour rather than implementation, keep each test independent, and make a failing test's name say what broke.
Linting, debugging, types and performance
RuboCop checks code against the community Ruby Style Guide and many correctness rules, and fixes most offences automatically with rubocop -a. Teams tune it with a .rubocop.yml; Standard is a zero-configuration wrapper for teams that would rather not debate settings. Run it in your editor and in CI.
Debugging. The debug gem ships with Ruby. Put binding.break (or debugger) in your code, run the program, and you get a prompt at that line where you can inspect variables, step through code and evaluate expressions; binding.irb opens an irb session in place. Most editors can attach to it for graphical debugging. And never underestimate p and pp at the right line.
Types. Ruby is dynamically typed, and many teams are happy that way, relying on tests. For those who want static checking, there are two main approaches. RBS, Ruby's official signature language, describes types in separate .rbs files; Ruby ships with rbs and TypeProf (which infers signatures from code), and Steep checks code against them. Sorbet, created at Stripe, uses signatures written inline with a sig method and is used in several large codebases. Both can be adopted gradually, file by file.
Performance. CRuby includes YJIT, a just-in-time compiler that typically makes real applications noticeably faster. Enable it with ruby --yjit or the environment variable RUBY_YJIT_ENABLE=1; recent Rails versions turn it on for you. Ruby 4.0 also contains ZJIT, a newer, experimental JIT. As with all performance work, measure with a profiler before changing code.
Ruby on Rails, in overview
Rails is a full-stack web framework built on two principles: convention over configuration (follow the naming conventions and almost nothing needs configuring) and don't repeat yourself. A new application (rails new) comes with:
- Active Record, the object-relational mapper: each database table is a class, each row an object, columns become attributes (through the metaprogramming you saw earlier), and associations and validations are class macros (
has_many :orders,validates :email, presence: true). Migrations describe schema changes in Ruby. - Action Controller and routing: URLs map to controller actions, which load models and render responses. The request cycle includes the security defaults from good practice: CSRF protection, parameter filtering, escaped output.
- Action View templates (ERB by default) and Hotwire (Turbo and Stimulus) for interactive pages that send HTML over the wire instead of building everything in JavaScript.
- Active Job for background work, Action Mailer for email, Action Cable for WebSockets, and Active Storage for file uploads.
- Since Rails 8 (2024), database-backed defaults for jobs, caching and WebSockets (Solid Queue, Solid Cache, Solid Cable), a built-in authentication generator, and Kamal for deploying to your own servers.
- A test framework (Minitest), generators, a console (
bin/rails console) and much more.
Rails is a large framework and repays learning properly: the official Rails Guides are excellent and start from a blank project. Lighter alternatives exist for smaller services: Sinatra (a few lines per route), Roda and Hanami.
A complete project: splitting the costs of a trip
Four friends share a trip. Each records what they paid and who it was for, and the program works out who owes whom and the fewest obvious payments to settle up. It uses most of this course: Data value objects, money as integer cents, a regular expression with named captures matched with case/in, a custom error hierarchy, Enumerable throughout, and Minitest tests in the same file.
# frozen_string_literal: true
require "minitest"
# Split the costs of a shared trip and work out who should pay whom.
module Splitter
class Error < StandardError; end
class ParseError < Error; end
# An amount of money in cents. Immutable.
Money = Data.define(:cents) do
def self.parse(text)
raise ParseError, "not an amount: #{text.inspect}" unless text.match?(/\A\d+(\.\d{1,2})?\z/)
whole, fraction = text.split(".")
new(cents: Integer(whole, 10) * 100 + (fraction || "").ljust(2, "0").to_i)
end
def to_s = format("%s%d.%02d", cents.negative? ? "-" : "", cents.abs / 100, cents.abs % 100)
end
Expense = Data.define(:payer, :amount, :what, :shared_by)
Transfer = Data.define(:from, :to, :amount) do
def to_s = "#{from} pays #{to} #{amount}"
end
LINE = /\A(?<payer>\p{L}+) paid (?<amount>\S+) for (?<what>[^;]+); split: (?<who>.+)\z/
class Trip
attr_reader :people
def initialize(people)
@people = people.sort.freeze
@expenses = []
end
# "Amina paid 90.00 for dinner; split: all" or "...; split: Amina, Chen"
def record(line)
case LINE.match(line.strip)
in nil
raise ParseError, "cannot read: #{line.strip.inspect}"
in { payer:, amount:, what:, who: }
shared_by = who == "all" ? people : who.split(/,\s*/)
add(Expense.new(payer:, amount: Money.parse(amount), what:, shared_by:))
end
end
def add(expense)
unknown = [expense.payer, *expense.shared_by].uniq - people
raise Error, "not on this trip: #{unknown.join(', ')}" if unknown.any?
@expenses << expense
self
end
def total = Money.new(cents: @expenses.sum { it.amount.cents })
# Positive: the trip owes this person. Negative: this person owes the trip.
def balances
cents = people.to_h { [it, 0] }
@expenses.each do |expense|
cents[expense.payer] += expense.amount.cents
shares(expense).each { |person, share| cents[person] -= share }
end
cents.transform_values { Money.new(cents: it) }
end
# Greedy settlement: the biggest debtor pays the biggest creditor, repeatedly.
def settlements
owed = balances.transform_values(&:cents)
debtors = owed.filter_map { |person, c| [person, -c] if c.negative? }.sort_by { |p, c| [-c, p] }
creditors = owed.filter_map { |person, c| [person, c] if c.positive? }.sort_by { |p, c| [-c, p] }
transfers = []
until debtors.empty? || creditors.empty?
(debtor, owes), (creditor, due) = debtors.first, creditors.first
paid = [owes, due].min
transfers << Transfer.new(from: debtor, to: creditor, amount: Money.new(cents: paid))
owes == paid ? debtors.shift : debtors[0] = [debtor, owes - paid]
due == paid ? creditors.shift : creditors[0] = [creditor, due - paid]
end
transfers
end
private
# Split an amount as evenly as possible; leftover cents go to the first names alphabetically.
def shares(expense)
base, extra = expense.amount.cents.divmod(expense.shared_by.size)
expense.shared_by.sort.each_with_index.to_h { |person, i| [person, base + (i < extra ? 1 : 0)] }
end
end
end
class SplitterTest < Minitest::Test
include Splitter
def trip = Trip.new(%w[Amina Bruno Chen])
def test_money_parsing
assert_equal 9050, Money.parse("90.5").cents
assert_equal "-3.07", Money.new(cents: -307).to_s
assert_raises(ParseError) { Money.parse("12.345") }
end
def test_shares_add_up_exactly
t = trip.record("Amina paid 100 for museum tickets; split: all")
assert_equal({ "Amina" => 6666, "Bruno" => -3333, "Chen" => -3333 }, t.balances.transform_values(&:cents))
assert_equal 0, t.balances.values.sum(&:cents)
end
def test_settlements_leave_everyone_even
t = trip
t.record("Amina paid 90.00 for dinner; split: all")
t.record("Chen paid 25.50 for a taxi; split: Bruno, Chen")
remaining = t.balances.transform_values(&:cents)
t.settlements.each do |transfer|
remaining[transfer.from] += transfer.amount.cents
remaining[transfer.to] -= transfer.amount.cents
end
assert remaining.values.all?(&:zero?)
end
def test_rejects_strangers_and_nonsense
assert_raises(Error) { trip.record("Dana paid 10 for snacks; split: all") }
error = assert_raises(ParseError) { trip.record("Amina bought lunch") }
assert_match(/cannot read/, error.message)
end
end
trip = Splitter::Trip.new(%w[Amina Bruno Chen Dilnoza])
[
"Amina paid 180.00 for the guesthouse; split: all",
"Bruno paid 64.20 for groceries; split: all",
"Chen paid 25.50 for a taxi; split: Chen, Dilnoza",
"Dilnoza paid 12 for museum tickets; split: Amina, Dilnoza",
"Bruno paid twelve for snacks; split: all",
].each do |line|
trip.record(line)
rescue Splitter::Error => e
puts "skipped (#{e.message})"
end
puts "Total spent: #{trip.total}"
trip.balances.each { |person, money| puts format(" %-8s %8s", person, money) }
puts "To settle up:"
trip.settlements.each { puts " #{it}" }
puts
exit Minitest.run(%w[--seed 2026])skipped (not an amount: "twelve")
Total spent: 281.70
Amina 112.95
Bruno 3.15
Chen -48.30
Dilnoza -67.80
To settle up:
Dilnoza pays Amina 67.80
Chen pays Amina 45.15
Chen pays Bruno 3.15
Run options: --seed 2026
# Running:
....
Finished in 0.003464s, 1154.6581 runs/s, 2886.6452 assertions/s.
4 runs, 10 assertions, 0 failures, 0 errors, 0 skipsHow it is built:
- Values.
Money,ExpenseandTransferareDataclasses: immutable, comparable by value, withto_sfor display.Money.parseaccepts at most two decimals and stores integer cents, so sums are exact; a line with "twelve" as the amount raises aParseErrorand is skipped with a message, while the other lines are recorded. - Parsing with patterns. A
MatchDatafrom a regular expression with named groups can be matched as a hash (since Ruby 3.3), soin { payer:, amount:, what:, who: }both checks that the line was understood and extracts the four parts.in nilhandles lines that do not match at all. - Validation at the boundary.
addrefuses expenses involving people who are not on the trip, so the rest of the code can trust its data. - Fair shares.
divmodsplits an amount into equal shares plus leftover cents, which go to the first names alphabetically, so the shares always add up to the exact amount. The balances always sum to zero, and a test checks it. - Settling up.
settlementsrepeatedly matches the person who owes most with the person owed most. This greedy method settles everyone and uses at most one payment fewer than the number of people with a non-zero balance; finding the absolute minimum number of payments is a much harder problem that a small trip does not need. - Tests. The four tests cover parsing, exact shares, the property that applying the settlements leaves everyone even, and rejection of bad input.
Minitest.runreturns true or false, andexitpasses that on as the program's exit status, so a CI system can tell whether the tests passed.
As a real project, this would become a gem layout: lib/splitter/money.rb, lib/splitter/trip.rb and so on, a test/ folder with one file per class, a Gemfile, a Rakefile whose default task runs the tests and RuboCop, and an executable in exe/ that reads expense lines from a file. Ideas for extending it: support several currencies by adding a currency to Money; read lines from a file given on the command line with ARGF; or add a --json option that prints the settlements with the standard json library.
Where to go next
- Build a Rails application by following the official Getting Started with Rails guide, and write tests as you go.
- Read the Ruby documentation at docs.ruby-lang.org, especially
Enumerable,String,Hashand the syntax pages, and the release notes (NEWS) each December. - Read good Ruby code. Popular gems on GitHub are some of the most carefully written Ruby there is, and contributing documentation or a small fix is a welcoming way in.
- Join the community. Ruby's community is known for its friendliness; local meetups and conferences around the world, and the forums linked from ruby-lang.org, are good places to ask questions.
Common misunderstandings
Misconception
"bundle update is how you install the gems for a project." bundle install installs exactly what Gemfile.lock says; bundle update picks newer versions and rewrites the lock file. Run update deliberately, one gem at a time where possible, then run the tests and commit the new lock file.
Misconception
"Tests that pass in the order I wrote them are fine." Minitest shuffles test order on purpose. If a test fails only with certain seeds, two tests share state (a global, a class variable, a file on disk). Fix the sharing; do not pin the order.
Misconception
"Rails is a language, or Ruby is just Rails." Rails is a framework written in Ruby. Everything in this course applies inside a Rails application, and Rails adds its own conventions and many extensions to core classes (from ActiveSupport) on top. Learning Ruby first, as you have, makes Rails far less magical.
Exercises
1. Gems, testing, Rails and a complete project
Warm-upHumanA Gemfile says gem "nokogiri", "~> 1.16". Which of these versions may Bundler choose? List them.
1.15.9, 1.16.0, 1.19.3, 2.0.0
2. Gems, testing, Rails and a complete project
Warm-upHumanYou clone a colleague's Ruby project, which has a Gemfile and a committed Gemfile.lock. What do you run to get the same gems they have?
3. Gems, testing, Rails and a complete project
Warm-upHumanIn Minitest's progress line (such as ..F.S), which single character marks a skipped test?
4. Gems, testing, Rails and a complete project
CoreHumanA test fails on the CI server but passes on your laptop, and the CI log begins with Run options: --seed 31337. What is the most useful next step?
5. Gems, testing, Rails and a complete project
CoreComputationalUsing the project's Splitter::Trip:
t = Splitter::Trip.new(%w[Amina Bruno Chen])
t.record("Amina paid 10.00 for snacks; split: all")
p t.balances.transform_values(&:cents)
What is Amina's balance, in cents?
6. Gems, testing, Rails and a complete project
CoreComputationalWhat does this print?
t = Splitter::Trip.new(%w[Ana Ben])
t.record("Ana paid 30 for lunch; split: all")
puts t.settlements.map(&:to_s)
7. Gems, testing, Rails and a complete project
StretchComputationalWhat does puts Splitter::Money.new(cents: -5) print?
Further reading and resources
- RubyGems GuidesInstalling, using and publishing gems.
- BundlerGemfiles, lock files, groups and every bundle command.
- MinitestThe testing library that ships with Ruby, with its documentation.
- RSpec
- RuboCopThe standard linter and formatter for Ruby, based on the community style guide.
- Ruby on Rails GuidesThe official guides, starting with Getting Started with Rails.
- RBSRuby's official type signature language.