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 Shelf namespace holds Book, Author, Isbn (a validated value object), Loan and loan states, a catalogue interface with an in-memory implementation, and domain errors under Shelf::Error.

  • exe/shelf is a command-line program that searches, lends and returns books and imports and exports JSON.

  • A gemspec, a Gemfile, a Rakefile, 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:

  1. Make a shelf directory and save each listing below in it, at the path in the listing’s title (lib/shelf/isbn.rb goes in shelf/lib/shelf/).

  2. Save the example in the same shelf directory, for instance as example.rb.

  3. From that directory, run ruby -Ilib example.rb (add -w to see warnings, as the pages do). -Ilib puts lib/ on the load path, so require "shelf" loads lib/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.

lib/shelf.rb
# 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
lib/shelf/version.rb
# 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")).

lib/shelf/isbn.rb
# 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
lib/shelf/author.rb
# frozen_string_literal: true

module Shelf
  Author = Data.define(:name)
end
lib/shelf/book.rb
# frozen_string_literal: true

module Shelf
  Book = Data.define(:isbn, :title, :author) do
    def to_s = "#{title} by #{author.name}"
  end
end

Loans

A Loan pairs a book with one of four states and describes itself with a case/in pattern match.

lib/shelf/loan.rb
# 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.

lib/shelf/catalog.rb
# 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
lib/shelf/store/memory.rb
# 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

Refinement

The gem ships one refinement, String#title_case, which is active only in files that say using Shelf::Refinements::TitleCase.

lib/shelf/refinements/title_case.rb
# 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.

shelf.gemspec
# 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
Gemfile
# frozen_string_literal: true

source "https://rubygems.org"

gemspec

gem "minitest", "~> 6.0"
gem "rake", "~> 13.0"
gem "rubocop", "~> 1.92", require: false
.rubocop.yml
AllCops:
  TargetRubyVersion: 4.0
  NewCops: enable
  SuggestExtensions: false
Style/Documentation:
  Enabled: false
Style/StringLiterals:
  EnforcedStyle: double_quotes

New here? Read in this order

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.

mindmap root((Ruby Reference)) Getting started Installing and tools Versions and releases Program structure Core language Literals and variables Methods and blocks Control flow Exceptions Object model Classes and modules Method lookup Visibility Refinements Core types Strings and symbols Arrays and hashes Ranges and Set Struct and Data Time and regexps Iteration Enumerable Enumerators Pattern matching Metaprogramming Dynamic dispatch Hooks and eval Reflection Concurrency Threads and the GVL Fibers Ractors Tooling RubyGems and Bundler Rake and gems IRB and debug Documentation Standard library IO and processes Networking Serialization Security Quality Minitest and RSpec RBS and types RuboCop Design patterns Internals Prism and YARV YJIT and ZJIT Garbage collector C extensions and Wasm

What’s covered

Getting started

Page What it covers

Getting Started

what Ruby is for, installing it, the tools (ruby, irb, ri, gem, bundle), Hello world, error messages and the shelf gem

Versions, Releases and Compatibility

release cycle, branch maintenance phases, version constants, warnings and how features are decided

Program Structure and Lexical Elements

source files, encodings, comments, magic comments, tokens, keywords and naming conventions

Design Philosophy and Coming from Other Languages

the design ideas behind Ruby and a map from other languages

IDEs & Tools

the IDEs and editors commonly used for Ruby, with links to RubyMine, Ruby LSP and other editors

Core language

Page What it covers

Literals

numbers, strings, heredocs, percent literals, symbols, arrays, hashes, ranges, regexps and lambdas

Variables, Constants and Scope

local, instance, class and global variables, constants, scope gates and closures

Assignment and Multiple Assignment

assignment as an expression,

=, splats and destructuring

Operators and Precedence

operator methods, the precedence table, truthiness and short-circuiting

Control Expressions

if, unless, case, loops, break, next, redo, catch and throw

Methods and Parameters

def, every parameter kind and its order, endless methods and return values

Calling Methods and Argument Forwarding

call syntax, keyword arguments, safe navigation and argument forwarding

Blocks, Procs and Lambdas

yield, blocks, procs, lambdas, it and numbered parameters, closures and composition

Exceptions and Error Handling

raise, rescue, ensure, retry, the exception hierarchy and custom errors

Object model

Page What it covers

Classes and Objects

class, initialize, attributes, inspect and to_s, constants and class state

Modules and Mixins

namespaces, include, prepend, extend, module_function and the Comparable and Enumerable protocols

Singleton Classes and Class-Level Behavior

singleton methods, class << self, class methods and class-level instance variables

Method Lookup and super

the ancestors chain, super forms and how mixins change lookup

Visibility and Encapsulation

public, private, protected and the call-site rules

Refinements and Monkey Patching

open classes, monkey patching risks, prepend and refinements

Conversions and Coercion

to_s versus to_str, Kernel conversion functions and coerce

Equality, Hashing and Comparison

equal?, ==, eql?, hash, ===, <⇒ and Comparable

Object Lifecycle, Freezing and Copying

new, dup, clone, shallow versus deep copies and freeze

Core types

Page What it covers

Numbers

Integer, Float, Rational, Complex, rounding and number formatting

Strings

creating, mutating, slicing, searching and formatting strings, chilled literals

Encodings and Unicode

bytes and encodings, UTF-8, normalization and conversion errors

Symbols

interned identifiers, symbols versus strings and to_proc

Arrays

creating, indexing, slicing, mutating, sorting and searching arrays

Hashes

literals, defaults, iteration, transformation and the 3.4 inspect format

Ranges

inclusive, exclusive, endless and beginless ranges, step and arithmetic sequences

Struct, Data and Value Objects

Struct, Data and value objects for the shelf domain

Sets

the core Set class, set algebra and subset tests

Time and Dates

Time, Date, time zones, formatting, parsing and monotonic clocks

Regular Expressions

Onigmo syntax, matching, named captures, gsub and timeouts

Iteration and pattern matching

Page What it covers

Enumerable

the each protocol and the full Enumerable method catalogue

Enumerators and Lazy Evaluation

external iteration, Enumerator::Lazy, chains and products

Pattern Matching

case/in, find, hash and array patterns, pin, guards and deconstruct

Metaprogramming and reflection

Page What it covers

Dynamic Dispatch and Method Definition

send, public_send, define_method, method_missing and Method objects

Hooks, eval and DSLs

inherited, included and other hooks, instance_eval, class_eval and DSL design

Reflection, Introspection and Tracing

asking objects about themselves, Binding, TracePoint and ObjectSpace

Concurrency

Page What it covers

Threads and the GVL

Thread, Mutex, Queue, Monitor, the GVL and thread safety

Fibers and the Fiber Scheduler

Fiber, generators, the Fiber scheduler and non-blocking I/O

Ractors

Ractor isolation, Ractor::Port and shareable objects

Code organization, tooling and packaging

Page What it covers

Code Loading: require and autoload

require, require_relative, load, the load path and autoload

RubyGems and Bundler

gems, the gem command, Gemfile, Gemfile.lock, groups and default versus bundled gems

Creating and Publishing Gems, and Rake

bundle gem, the gemspec, building, publishing and Rake

Ruby Command Line and Environment

every ruby option, one-liners and environment variables

IRB and Debugging

IRB, the debug gem, breakpoints and post-mortem debugging

Documentation with RDoc and YARD

RDoc, YARD, ri and documentation comments

Command-Line Programs

ARGV, OptionParser, exit codes, standard streams and executables

Standard library

Page What it covers

IO, Files and Directories

File, Dir, Pathname, IO, tempfiles and file system pitfalls

Processes, Signals and Shell

system, spawn, Open3, Process, signals and shell escaping

Networking and HTTP

sockets, URI, Net::HTTP, timeouts and TLS

Serialization: JSON, YAML, CSV and Marshal

JSON, YAML, CSV and Marshal with safe loading

Standard Library Tour

default gems, bundled gems and the most useful libraries

Security

injection, deserialization, command execution, secrets and supply chain

Quality

Page What it covers

Testing with Minitest

Minitest tests, specs, doubles, fixtures and running suites

RSpec and Test Doubles

RSpec, matchers, doubles, spies and verifying doubles

Type Checking with RBS, TypeProf, Steep and Sorbet

RBS signatures, TypeProf, Steep and Sorbet

Style, Linting and Static Analysis

warnings, RuboCop, the Ruby Style Guide and static analysis

Design and practice

Page What it covers

Idioms, Style and Clean Code

naming, small methods, guard clauses and idiomatic Ruby

SOLID and Design Patterns

SOLID, DRY, KISS and the Gang of Four patterns in Ruby

Application Architecture in Plain Ruby

layers, service objects, repositories and boundaries without a framework

Common Mistakes and Gotchas

frequent errors with real output and their fixes

Performance and internals

Page What it covers

Performance, Benchmarking and Profiling

Benchmark, benchmark-ips, profilers and algorithmic hot spots

YJIT, ZJIT and the VM

Prism, YARV, YJIT, ZJIT and the instruction sequences

Garbage Collection and Memory

heap pages, generational GC, GC.stat and tuning

Interop

Page What it covers

C Extensions, FFI and WebAssembly

C extensions, Fiddle, the ffi gem and ruby.wasm

Evolution and reference

Page What it covers

What’s New and Migrating Older Code

a migration guide from Ruby 3.0 to 4.0 and the older code you may meet

Cheat sheet

Page What it covers

Cheat Sheet (PDF)

a one-page A4 summary of the whole section with a strip of what changed since older tutorials

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

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 4.0 documentation: entry points and C extensions

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.

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.