Ruby Reference
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. The reference material consulted while preparing these pages is listed in the section bibliography. |
This section is written against Ruby 4.0 (the current stable release is Ruby 4.0.7), checked on 2026-10-18. Ruby publishes a new minor or major version every 25 December and patch releases in between; the 4.0 branch (released on 2025-12-25) and the 3.4 branch are in normal maintenance, 3.3 is in security maintenance, and Ruby 4.1 is only available as a preview (4.1.0-preview1 was announced on 2026-10-12; the final release is expected on 2026-12-25), so nothing here depends on it. Features newer than Ruby 3.0 are marked with the version that introduced them, for example it and chilled strings (3.4), Data (3.2), core Set (autoloaded since 3.2, in core since 4.0) and Ractor::Port (4.0). Examples were syntax-checked, run and linted with Ruby 4.0.7 and RuboCop with its default configuration.
What Ruby is
Ruby is a dynamic, interpreted, garbage-collected and purely object-oriented language designed by Yukihiro "Matz" Matsumoto, who released it in 1995 with the goal of programmer happiness. Every value is an object, blocks and mixins replace most inheritance hierarchies and callbacks, classes are open, and metaprogramming is a normal tool rather than a trick. The reference implementation, CRuby, parses source with Prism, compiles it to YARV bytecode, runs it on a virtual machine with a global VM lock, and can compile hot methods to machine code with YJIT or the newer ZJIT. Around the language sit the ruby, irb, ri, gem, bundle and rake commands, a large standard library split into default and bundled gems, and a package ecosystem on RubyGems. Ruby powers web back ends, scripts and automation, and developer tools such as Homebrew, CocoaPods and fastlane.
The shelf scenario
The examples across the section share one small, original domain: shelf, a Ruby gem for a library catalogue. It is deliberately the same domain as the Rust Reference and the Go Reference, so you can compare the languages on the same types.
-
The
Shelfnamespace holdsBook,Author,Isbn(a validated value object),Loanand loan states, a catalogue interface with an in-memory implementation, and domain errors underShelf::Error. -
exe/shelfis a command-line program that searches, lends and returns books and imports and exports JSON. -
A gemspec, a
Gemfile, aRakefile, Minitest and RSpec tests, RBS signatures and a RuboCop configuration grow alongside the code.
The pages build on each other, and the cheat sheet summarises them.
The shelf gem source
These listings are the whole library that the examples load with require "shelf". To run an example, recreate the gem:
-
Make a
shelfdirectory and save each listing below in it, at the path in the listing’s title (lib/shelf/isbn.rbgoes inshelf/lib/shelf/). -
Save the example in the same
shelfdirectory, for instance asexample.rb. -
From that directory, run
ruby -Ilib example.rb(add-wto see warnings, as the pages do).-Ilibputslib/on the load path, sorequire "shelf"loadslib/shelf.rb, which loads the rest.
The library needs only Ruby 4.0 and its standard library; nothing has to be installed to run the examples. The gemspec and the Gemfile are needed only for bundle install, the tests, RuboCop and building the gem, and the gemspec also lists the exe/shelf command shown in Getting Started. Examples that reopen one of these classes, or that define classes of their own, run unchanged on top of it. Application Architecture in Plain Ruby and Command-Line Programs add further files under lib/shelf/, and each page shows them.
Entry point and version
lib/shelf.rb loads every file of the library, defines the Shelf::Error base class and holds the global configuration (a store and a loan period). lib/shelf/version.rb is a file of its own so that the gemspec can read the version without loading the library.
# frozen_string_literal: true
require_relative "shelf/version"
require_relative "shelf/isbn"
require_relative "shelf/author"
require_relative "shelf/book"
require_relative "shelf/loan"
require_relative "shelf/store/memory"
require_relative "shelf/catalog"
require_relative "shelf/refinements/title_case"
# A small library catalogue used as the running example.
module Shelf
class Error < StandardError; end
Config = Struct.new(:store, :loan_days)
def self.config
@config ||= Config.new(Store::Memory.new, 14)
end
def self.configure
yield config
config
end
end
# frozen_string_literal: true
module Shelf
VERSION = "0.1.0"
end
Value objects
Isbn, Author and Book are immutable Data classes. Isbn removes hyphens and checks the ISBN-13 check digit in initialize, so an invalid ISBN never exists. All three accept positional or keyword arguments (Shelf::Isbn.new("978-0-306-40615-7") or Shelf::Isbn.new(digits: "9780306406157")).
# frozen_string_literal: true
module Shelf
# An ISBN-13 value object.
Isbn = Data.define(:digits) do
def initialize(digits:)
cleaned = digits.to_s.delete("-")
raise ArgumentError, "invalid ISBN: #{digits}" unless valid?(cleaned)
super(digits: cleaned)
end
def to_s = digits
private
def valid?(value)
return false unless value.match?(/\A\d{13}\z/)
sum = value.chars.map(&:to_i).each_with_index.sum { |d, i| i.even? ? d : d * 3 }
(sum % 10).zero?
end
end
end
# frozen_string_literal: true
module Shelf
Author = Data.define(:name)
end
# frozen_string_literal: true
module Shelf
Book = Data.define(:isbn, :title, :author) do
def to_s = "#{title} by #{author.name}"
end
end
Source: Ruby 4.0 documentation: Data
Loans
A Loan pairs a book with one of four states and describes itself with a case/in pattern match.
# frozen_string_literal: true
module Shelf
# A loan of a book, with a state driven by pattern matching.
class Loan
STATES = %i[available lent overdue returned].freeze
attr_reader :book, :state
def initialize(book, state: :available)
raise ArgumentError, "unknown state: #{state}" unless STATES.include?(state)
@book = book
@state = state
end
def describe
case { state:, book: }
in { state: :available } then "#{book.title} is on the shelf"
in { state: :lent | :overdue => s } then "#{book.title} is #{s}"
in { state: :returned } then "#{book.title} came back"
end
end
end
end
Catalogue and store
Catalog is Enumerable over the books of a store and guards the store with a mutex. A store is any object with all and add; Store::Memory, an array in memory, is the default one, taken from Shelf.config.
# frozen_string_literal: true
module Shelf
# The catalogue, guarded by a mutex.
class Catalog
include Enumerable
def initialize(store: Shelf.config.store)
@store = store
@mutex = Thread::Mutex.new
end
def add(book)
@mutex.synchronize { @store.add(book) }
self
end
def each(&)
return enum_for(:each) unless block_given?
@mutex.synchronize { @store.all }.each(&)
end
end
end
# frozen_string_literal: true
module Shelf
module Store
# In-memory adapter, duck-typed with #all and #add.
class Memory
def initialize = @books = []
def all = @books.dup
def add(book)
@books << book
self
end
end
end
end
Source: Ruby 4.0 documentation: Enumerable and Thread::Mutex
Refinement
The gem ships one refinement, String#title_case, which is active only in files that say using Shelf::Refinements::TitleCase.
# frozen_string_literal: true
module Shelf
module Refinements
# Refines String instead of monkey patching it.
module TitleCase
refine String do
def title_case = split.map(&:capitalize).join(" ")
end
end
end
end
Gemspec, Gemfile and RuboCop configuration
The gemspec describes the gem, the Gemfile adds the development tools, and .rubocop.yml is the configuration the examples are linted with.
# frozen_string_literal: true
require_relative "lib/shelf/version"
Gem::Specification.new do |spec|
spec.name = "shelf"
spec.version = Shelf::VERSION
spec.authors = ["Example Author"]
spec.summary = "A small library catalogue."
spec.homepage = "https://example.com/shelf"
spec.license = "MIT"
spec.required_ruby_version = ">= 4.0"
spec.metadata["rubygems_mfa_required"] = "true"
spec.files = Dir["lib/**/*.rb", "exe/*", "sig/**/*.rbs"]
spec.bindir = "exe"
spec.executables = ["shelf"]
spec.require_paths = ["lib"]
end
# frozen_string_literal: true
source "https://rubygems.org"
gemspec
gem "minitest", "~> 6.0"
gem "rake", "~> 13.0"
gem "rubocop", "~> 1.92", require: false
AllCops:
TargetRubyVersion: 4.0
NewCops: enable
SuggestExtensions: false
Style/Documentation:
Enabled: false
Style/StringLiterals:
EnforcedStyle: double_quotes
New here? Read in this order
-
Getting Started — install Ruby, the tools, a first program
-
Methods and Parameters and Blocks, Procs and Lambdas — how Ruby passes behaviour around
-
RubyGems and Bundler — packaging and dependencies
Then pick topics as you need them, and keep the cheat sheet at hand. If you know an older tutorial or one of the books in the bibliography, start with What’s New and Migrating Older Code.
What’s covered
Getting started
| Page | What it covers |
|---|---|
what Ruby is for, installing it, the tools (ruby, irb, ri, gem, bundle), Hello world, error messages and the shelf gem |
|
release cycle, branch maintenance phases, version constants, warnings and how features are decided |
|
source files, encodings, comments, magic comments, tokens, keywords and naming conventions |
|
the design ideas behind Ruby and a map from other languages |
|
the IDEs and editors commonly used for Ruby, with links to RubyMine, Ruby LSP and other editors |
Core language
| Page | What it covers |
|---|---|
numbers, strings, heredocs, percent literals, symbols, arrays, hashes, ranges, regexps and lambdas |
|
local, instance, class and global variables, constants, scope gates and closures |
|
assignment as an expression, |
|
=, splats and destructuring |
|
operator methods, the precedence table, truthiness and short-circuiting |
|
if, unless, case, loops, break, next, redo, catch and throw |
|
def, every parameter kind and its order, endless methods and return values |
|
call syntax, keyword arguments, safe navigation and argument forwarding |
|
yield, blocks, procs, lambdas, it and numbered parameters, closures and composition |
|
raise, rescue, ensure, retry, the exception hierarchy and custom errors |
Object model
| Page | What it covers |
|---|---|
class, initialize, attributes, inspect and to_s, constants and class state |
|
namespaces, include, prepend, extend, module_function and the Comparable and Enumerable protocols |
|
singleton methods, class << self, class methods and class-level instance variables |
|
the ancestors chain, super forms and how mixins change lookup |
|
public, private, protected and the call-site rules |
|
open classes, monkey patching risks, prepend and refinements |
|
to_s versus to_str, Kernel conversion functions and coerce |
|
equal?, ==, eql?, hash, ===, <⇒ and Comparable |
|
new, dup, clone, shallow versus deep copies and freeze |
Core types
| Page | What it covers |
|---|---|
Integer, Float, Rational, Complex, rounding and number formatting |
|
creating, mutating, slicing, searching and formatting strings, chilled literals |
|
bytes and encodings, UTF-8, normalization and conversion errors |
|
interned identifiers, symbols versus strings and to_proc |
|
creating, indexing, slicing, mutating, sorting and searching arrays |
|
literals, defaults, iteration, transformation and the 3.4 inspect format |
|
inclusive, exclusive, endless and beginless ranges, step and arithmetic sequences |
|
Struct, Data and value objects for the shelf domain |
|
the core Set class, set algebra and subset tests |
|
Time, Date, time zones, formatting, parsing and monotonic clocks |
|
Onigmo syntax, matching, named captures, gsub and timeouts |
Iteration and pattern matching
| Page | What it covers |
|---|---|
the each protocol and the full Enumerable method catalogue |
|
external iteration, Enumerator::Lazy, chains and products |
|
case/in, find, hash and array patterns, pin, guards and deconstruct |
Metaprogramming and reflection
| Page | What it covers |
|---|---|
send, public_send, define_method, method_missing and Method objects |
|
inherited, included and other hooks, instance_eval, class_eval and DSL design |
|
asking objects about themselves, Binding, TracePoint and ObjectSpace |
Concurrency
| Page | What it covers |
|---|---|
Thread, Mutex, Queue, Monitor, the GVL and thread safety |
|
Fiber, generators, the Fiber scheduler and non-blocking I/O |
|
Ractor isolation, Ractor::Port and shareable objects |
Code organization, tooling and packaging
| Page | What it covers |
|---|---|
require, require_relative, load, the load path and autoload |
|
gems, the gem command, Gemfile, Gemfile.lock, groups and default versus bundled gems |
|
bundle gem, the gemspec, building, publishing and Rake |
|
every ruby option, one-liners and environment variables |
|
IRB, the debug gem, breakpoints and post-mortem debugging |
|
RDoc, YARD, ri and documentation comments |
|
ARGV, OptionParser, exit codes, standard streams and executables |
Standard library
| Page | What it covers |
|---|---|
File, Dir, Pathname, IO, tempfiles and file system pitfalls |
|
system, spawn, Open3, Process, signals and shell escaping |
|
sockets, URI, Net::HTTP, timeouts and TLS |
|
JSON, YAML, CSV and Marshal with safe loading |
|
default gems, bundled gems and the most useful libraries |
|
injection, deserialization, command execution, secrets and supply chain |
Quality
| Page | What it covers |
|---|---|
Minitest tests, specs, doubles, fixtures and running suites |
|
RSpec, matchers, doubles, spies and verifying doubles |
|
RBS signatures, TypeProf, Steep and Sorbet |
|
warnings, RuboCop, the Ruby Style Guide and static analysis |
Design and practice
| Page | What it covers |
|---|---|
naming, small methods, guard clauses and idiomatic Ruby |
|
SOLID, DRY, KISS and the Gang of Four patterns in Ruby |
|
layers, service objects, repositories and boundaries without a framework |
|
frequent errors with real output and their fixes |
Performance and internals
| Page | What it covers |
|---|---|
Benchmark, benchmark-ips, profilers and algorithmic hot spots |
|
Prism, YARV, YJIT, ZJIT and the instruction sequences |
|
heap pages, generational GC, GC.stat and tuning |
Evolution and reference
| Page | What it covers |
|---|---|
a migration guide from Ruby 3.0 to 4.0 and the older code you may meet |
Ruby on Rails
Ruby on Rails is out of scope for this section: it covers the Ruby language, core classes and standard library, and plain-Ruby application design (see Application Architecture in Plain Ruby), without any framework. The Rails-specific material of the second book in the bibliography (Dementyev, layered design with Active Record, controllers, jobs and views) therefore has no page here and belongs in a future Rails section; where a page needs a framework comparison it names Rails in prose only.
Bibliography
Every source used on any page of this section is listed here, each linked to its official website; the individual pages list the subset they derive from under their own == References heading. The official Ruby documentation always wins: the books are consulted references, not the primary source, and on any discrepancy, or wherever a book is silent on a later feature, the official documentation decides.
Books
-
Carleton DiLeo, Clean Ruby: A Guide to Crafting Better Code for Rubyists, 2nd ed., Apress, 2026, print ISBN 979-8-8688-2642-9, eBook ISBN 979-8-8688-2643-6, DOI 10.1007/979-8-8688-2643-6 — publisher page on SpringerLink and the companion code at Apress/clean-ruby-2nd-ed
-
Vladimir Dementyev, Layered Design for Ruby on Rails Applications, 2nd ed., Packt Publishing, 2025, ISBN 978-1-80611-423-8 — publisher page at Packt and the companion code at PacktPublishing/Layered-Design-for-Ruby-on-Rails-Applications-Second-Edition
The pages cite the books by author and chapter (occasionally by printed page), and call out where they are outdated (the migration guide collects them); no text, listing or figure of either book is reproduced.
Official Ruby documentation and resources
-
ruby-lang.org, the documentation hub and the downloads page
ruby-lang.org pages
-
www.ruby-lang.org/en/documentation/ruby-from-other-languages
-
www.ruby-lang.org/en/documentation/ruby-from-other-languages/to-ruby-from-c-and-cpp
-
www.ruby-lang.org/en/documentation/ruby-from-other-languages/to-ruby-from-java
-
www.ruby-lang.org/en/documentation/ruby-from-other-languages/to-ruby-from-perl
-
www.ruby-lang.org/en/documentation/ruby-from-other-languages/to-ruby-from-php
-
www.ruby-lang.org/en/documentation/ruby-from-other-languages/to-ruby-from-python
Release announcements
Core and standard-library class pages
Every class and module page used, from the Ruby 4.0 documentation (plus Benchmark from the 3.4 documentation, the last release that shipped it as a default gem):
RubyGems and Bundler
The ruby/* repositories and sites
Community references
These are not official; the pages label them as community material. Version managers and installers are listed by ruby-lang.org but maintained independently.
-
cdn.jsdelivr.net/npm/@ruby/4.0-wasm-wasi@2.10.1/dist/browser.script.iife.js
-
rspec.info/features/3-13/rspec-core/command-line/only-failures
-
rspec.info/features/3-13/rspec-core/configuration/zero-monkey-patching-mode
-
rspec.info/features/3-13/rspec-core/example-groups/shared-context
-
rspec.info/features/3-13/rspec-core/example-groups/shared-examples
-
rspec.info/features/3-13/rspec-expectations/aggregating-failures
-
rspec.info/features/3-13/rspec-expectations/built-in-matchers
-
rspec.info/features/3-13/rspec-mocks/basics/allowing-messages
-
rspec.info/features/3-13/rspec-mocks/basics/expecting-messages
-
rspec.info/features/3-13/rspec-mocks/basics/null-object-doubles
-
rspec.info/features/3-13/rspec-mocks/basics/partial-test-doubles
Other implementations mentioned for comparison are JRuby, TruffleRuby and mruby. Ruby Changes is cited for version history only.
References
This landing page derives from every source of the section; they are all listed, with links to their official websites, in the Bibliography above.