Objects all the way down
You have been using objects since the first lesson: numbers, strings, arrays and hashes are all instances of classes, and you have called their methods. Now you will write your own.
Ruby's object model is small and consistent. Every object has a class; a class defines the methods its instances respond to; classes inherit from one superclass; and modules let you share methods across unrelated classes without inheritance. Ruby also bets heavily on duck typing: code asks whether an object can do something (does it respond to each? to <=>?), not what class it is. That is why Enumerable could turn the playlist from the last lesson into a full collection with one line, and why Ruby code tends to be built from small objects with clear responsibilities rather than deep class hierarchies.
This lesson covers classes, inheritance, modules and mixins, the method lookup chain that ties them together, and the value-object tools Struct and Data.
Defining classes
class Event
attr_reader :name, :capacity
# A class method: called on the class, often as an alternative constructor.
def self.from_line(line)
name, capacity = line.split(";")
new(name.strip, capacity: Integer(capacity))
end
def initialize(name, capacity:)
raise ArgumentError, "capacity must be positive" unless capacity.positive?
@name = name
@capacity = capacity
@attendees = []
end
def register(person)
return false if full? || registered?(person)
@attendees << person
true
end
def full? = @attendees.size >= capacity
def seats_left = capacity - @attendees.size
def attendees = @attendees.dup # hand out a copy, not our own array
def to_s = "#{name} (#{@attendees.size}/#{capacity})"
private
def registered?(person) = @attendees.include?(person)
end
class Workshop < Event
attr_reader :fee
def initialize(name, capacity:, fee:)
super(name, capacity:)
@fee = fee
end
def to_s = "#{super}, fee #{fee}"
end
talk = Event.from_line("Rust for Rubyists; 2")
p talk.register("Aiyana"), talk.register("Bram"), talk.register("Chiamaka"), talk.register("Aiyana")
puts talk, talk.full?, talk.seats_left
talk.attendees << "Intruder"
p talk.attendees
pottery = Workshop.new("Pottery", capacity: 8, fee: 25)
pottery.register("Dilnoza")
puts pottery
p pottery.is_a?(Event), Workshop.superclass, Workshop.ancestors.first(3)
p pottery.instance_variables
begin
pottery.registered?("Dilnoza")
rescue NoMethodError => e
puts "NoMethodError: #{e.message}"
end
begin
Event.new("Empty room", capacity: 0)
rescue ArgumentError => e
puts "ArgumentError: #{e.message}"
endtrue
true
false
false
Rust for Rubyists (2/2)
true
0
["Aiyana", "Bram"]
Pottery (1/8), fee 25
true
Event
[Workshop, Event, Object]
[:@name, :@capacity, :@attendees, :@fee]
NoMethodError: private method 'registered?' called for an instance of Workshop
ArgumentError: capacity must be positiveState lives in instance variables. Names starting with @ belong to one object. They are created by assigning to them, usually in initialize, which new calls. Instance variables are always private: code outside the object cannot reach @attendees directly.
Attribute methods. attr_reader :name defines a method name that returns @name. attr_writer defines name=, and attr_accessor both. Prefer readers; add writers only when outside code really should change the value, because every writer is a way for the object's rules to be bypassed. Note how attendees returns a copy (@attendees.dup): the caller's attempt to add "Intruder" changed only their copy, so the event's own list stayed at two names.
Class methods are defined with def self.from_line. Inside a class method, self is the class, so new(...) constructs an instance. Named constructors like this are common for parsing input into objects.
Visibility. Methods after the keyword private can only be called without an explicit receiver, from inside the object. Calling pottery.registered? from outside raised NoMethodError with a message saying the method is private. There is also protected, which allows calls from other instances of the same class (handy in comparison methods). Ruby has no "package" or "internal" visibility; teams communicate intent with namespaces and documentation.
Inheritance and super. Workshop < Event makes Workshop a subclass. Its initialize calls super(name, capacity:) to let Event do its part, then adds its own state. In to_s, a bare super (no parentheses) calls the parent's method with the same arguments, which is usually what you want; super() calls it with none. ancestors lists the classes Ruby searches for a method, in order.
Validation in the constructor. Event.new("Empty room", capacity: 0) raised ArgumentError immediately. An object that cannot be built in an invalid state saves every later method from checking.
Modules: namespaces and mixins
A module is like a class that cannot be instantiated. It has two jobs.
# A module as a namespace: it groups related constants, methods and classes.
module Units
KM_PER_MILE = 1.609344
def self.miles_to_km(miles) = (miles * KM_PER_MILE).round(2)
end
p Units.miles_to_km(26.2), Units::KM_PER_MILE
# A module as a mixin: Comparable supplies <, >, between?, clamp ... from <=>.
class Version
include Comparable
attr_reader :parts
def initialize(text)
@parts = text.split(".").map(&:to_i)
end
def <=>(other) = parts <=> other.parts
def to_s = parts.join(".")
end
versions = %w[1.10.0 1.2.9 1.2.10 0.9].map { Version.new(it) }
p versions.sort.map(&:to_s), versions.max.to_s
p Version.new("2.0") > Version.new("1.99"), Version.new("1.5").between?(Version.new("1.0"), Version.new("2.0"))
# Your own mixin: any class that provides #name gets #badge.
module Badge
def badge = "[#{name.upcase}]"
end
class Volunteer
include Badge
attr_reader :name
def initialize(name) = @name = name
end
puts Volunteer.new("Sefa").badge
# prepend puts the module *before* the class in the lookup, so it can wrap methods.
module Loud
def to_s = "#{super.upcase}!"
end
class Parrot
prepend Loud
def to_s = "polly wants a cracker"
end
puts Parrot.new
p Parrot.ancestors.first(3)
# extend adds a module's methods to a single object.
guest = Struct.new(:name).new("Ilse")
guest.extend(Badge)
puts guest.badge
# Duck typing: what matters is which methods an object has, not its class.
[Volunteer.new("Ana"), guest, 42].each do |thing|
puts thing.respond_to?(:badge) ? thing.badge : "#{thing.inspect} has no badge"
end42.16
1.609344
["0.9", "1.2.9", "1.2.10", "1.10.0"]
"1.10.0"
true
true
[SEFA]
POLLY WANTS A CRACKER!
[Loud, Parrot, Object]
[ILSE]
[ANA]
[ILSE]
42 has no badgeNamespaces. Units groups a constant and a helper method. Units::KM_PER_MILE reaches the constant and Units.miles_to_km calls the module method. Gems put all their classes inside one module named after the gem (Nokogiri::HTML, ActiveRecord::Base), so names from different libraries never clash.
Mixins with include. Including a module adds its methods to a class's instances, as if they were defined in the class. Comparable is the classic example: Version defines one method, <=>, and Comparable supplies <, >, ==, between? and clamp in terms of it. Because <=> compares the arrays of numbers, version 1.10.0 correctly sorts after 1.2.10, which a plain string comparison gets wrong. Sorting and max work too, since they also use <=>.
Your own modules work the same way. Badge needs only one thing from the class it is mixed into, a name method, and gives back a badge. That implicit contract ("you provide X, I provide Y") is how Enumerable (needs each) and Comparable (needs <=>) work, and it is worth writing down in a comment when you create your own.
prepend inserts the module before the class in the lookup chain, as Parrot.ancestors shows: [Loud, Parrot, Object]. So Loud#to_s runs first and can call super to reach the class's own to_s, then change its result. This is how instrumentation and logging libraries wrap methods without editing them.
extend adds a module's methods to one object only (its singleton class). Here the guest object gets badge, but other objects of its class do not. extend self inside a module, or module_function, is how a module makes its methods callable as Module.method.
Duck typing. The final loop does not ask "is this a Volunteer?" but "does it respond to badge?". Both the volunteer and the extended guest do, so both work. Idiomatic Ruby methods accept any object that behaves as needed: a method that reads lines can accept a File, a StringIO or an array of strings, as long as each responds to each_line or each.
The method lookup chain. When you call obj.foo, Ruby looks in obj's singleton class, then its class, then any prepended and included modules in order, then the superclass and its modules, all the way up to BasicObject. The first foo it finds runs, and super continues the search from that point. SomeClass.ancestors prints the chain, which is the first thing to check when a method does something surprising.
Struct, Data and equality
Many objects are just a few named values: a point, a coordinate, a money amount. Ruby has two shortcuts for them.
# Struct: a quick class with accessors, equality and to_a. Mutable.
Point = Struct.new(:x, :y) do
def distance_to(other) = Math.hypot(x - other.x, y - other.y)
end
a = Point.new(0, 0)
b = Point.new(3, 4)
p a.distance_to(b), a == Point.new(0, 0), b.to_a
a.x = 10
p a
# Data (Ruby 3.2): an immutable value object with keyword or positional construction.
Coordinate = Data.define(:lat, :lon) do
def initialize(lat:, lon:)
raise ArgumentError, "latitude #{lat} is out of range" unless (-90..90).cover?(lat)
super
end
def to_s = format("%.2f, %.2f", lat, lon)
end
home = Coordinate.new(lat: -1.29, lon: 36.82)
p home, home.frozen?
puts home.with(lat: -1.30)
p home == Coordinate.new(-1.29, 36.82)
p({ home => "home" }[Coordinate.new(lat: -1.29, lon: 36.82)])
begin
Coordinate.new(lat: 100, lon: 0)
rescue ArgumentError => e
puts "ArgumentError: #{e.message}"
end
begin
home.instance_variable_set(:@lat, 0)
rescue FrozenError => e
puts "FrozenError: #{e.message}"
end
# A plain class needs ==, eql? and hash to behave the same way as a value.
class Isbn
attr_reader :digits
def initialize(text) = @digits = text.delete("-")
def ==(other) = other.is_a?(Isbn) && digits == other.digits
alias eql? ==
def hash = digits.hash
end
p Isbn.new("12-34") == Isbn.new("1234"), [Isbn.new("12-34"), Isbn.new("1234")].uniq.size5.0
true
[3, 4]
#<struct Point x=10, y=0>
#<data Coordinate lat=-1.29, lon=36.82>
true
-1.30, 36.82
true
"home"
ArgumentError: latitude 100 is out of range
FrozenError: can't modify frozen Coordinate: #<data Coordinate lat=-1.29, lon=36.82>
true
1Definition— Struct
Struct.new(:x, :y) creates a class with an initialize for those fields, reader and writer methods, == that compares fields, to_a, and a readable inspect. The block adds your own methods. Struct instances are mutable (a.x = 10 works), which makes them handy for quick scripts but risky as shared values.
Definition— Data
Data.define(:lat, :lon) (Ruby 3.2) creates an immutable value class: no setters, instances are frozen, and construction requires every field, by keyword or by position. with(lat: -1.30) returns a copy with some fields changed. Overriding initialize with keyword parameters and calling super is the standard place for validation.
Data objects with equal fields are == and also work as equal hash keys, because Data defines eql? and hash from the fields: looking up a new Coordinate with the same numbers found "home". A plain class gets none of this by default: two separately created objects are different unless you define equality yourself, as Isbn does. The rule is that eql? and hash must agree: objects that are eql? must return the same hash, or hashes, sets and uniq will treat them as different. With the three methods defined, the two Isbn objects written differently count as one.
For new code, reach for Data when you need a small value, a plain class when an object has behaviour and changing state, and Struct mostly when you need mutability or are reading older code.
Class-level state, singleton methods and copies
Because classes are objects, they can have instance variables of their own, and because every object has a hidden singleton class, individual objects can have methods of their own. Both facts show up constantly in real Ruby code.
# Class-level state: an instance variable of the class object, separate for each subclass.
class Shape
def self.build(*args)
@built = built + 1
new(*args)
end
def self.built = @built || 0
end
class Circle < Shape
def initialize(radius) = @radius = radius
end
class Square < Shape
def initialize(side) = @side = side
end
Circle.build(1)
Circle.build(2)
Square.build(3)
p [Shape.built, Circle.built, Square.built]
# A class variable (@@) is shared with every subclass, which is rarely what you want.
class Counter
@@total = 0
def self.bump = @@total += 1
def self.total = @@total
end
class PageCounter < Counter
end
Counter.bump
PageCounter.bump
p [Counter.total, PageCounter.total]
# A singleton method belongs to one object only.
greeting = +"hello"
def greeting.shout = "#{upcase}!"
p greeting.shout, greeting.singleton_methods, "hi".respond_to?(:shout)
# dup copies the state; clone also keeps singleton methods and the frozen flag.
p greeting.dup.respond_to?(:shout), greeting.clone.respond_to?(:shout)
sealed = +"sealed"
sealed.freeze
p sealed.dup.frozen?, sealed.clone.frozen?
# to_s is for people, inspect is for programmers; override both when it helps.
class Temperature
def initialize(celsius) = @celsius = celsius
def to_s = "#{@celsius} °C"
def inspect = "#<Temperature #{@celsius}>"
end
t = Temperature.new(21.5)
puts t
p t
puts "Today: #{t}; readings: #{[t, Temperature.new(19)].inspect}"[0, 2, 1]
[2, 2]
"HELLO!"
[:shout]
false
false
true
false
true
21.5 °C
#<Temperature 21.5>
Today: 21.5 °C; readings: [#<Temperature 21.5>, #<Temperature 19>]Class instance variables. Inside a class method, self is the class, so @built is an instance variable of the class object. When Circle.build runs, self is Circle, so the count is stored on Circle; Square and Shape keep their own. That is exactly the separation you usually want for per-class registries, counters and configuration.
Class variables. @@total is shared by Counter and every subclass: bumping PageCounter changed the number Counter reports too. This is the trap mentioned in the misconceptions below, shown in action.
Singleton methods. def greeting.shout defines a method on that one string object; no other string has it. Class methods are the same idea: def self.build defines a singleton method on the class object. When you write class << self … end inside a class, you are opening the class's singleton class to add several such methods at once.
dup and clone. Both make a shallow copy. clone also copies the singleton methods and the frozen state; dup copies neither, which is why dup is the usual way to get a changeable copy of a frozen object.
to_s and inspect. Interpolation and puts call to_s; p, irb and the inspect of arrays and hashes call inspect. Defining both makes objects pleasant in output for users and in debugging for developers. A good inspect shows the class and the identifying state; Data and Struct generate one for you.
How Rubyists design with objects
Ruby makes classes cheap to write, and experienced Ruby developers take advantage of that. A few habits are widely shared in the community:
- Small objects with one job. A class that parses a file, validates rows, talks to a database and formats a report becomes hard to change. Four small classes, each named after what it does, are easier to read, test and reuse. Methods are short too, often under ten lines.
- Tell, don't ask. Instead of asking an object for its data and making decisions outside it (
if event.attendees.size < event.capacity …), tell the object what you want and let it decide (event.register(person)). The rules then live in one place. - Inject collaborators. An object that needs a clock, a mailer or a repository receives it in
initialize(often as a keyword argument with a sensible default) instead of creating it inside. Tests can then pass simple stand-ins, which the last lesson of this course relies on. - Prefer composition, keep hierarchies shallow. Inheritance is used sparingly, typically one level deep, for genuine "is a kind of" relationships. Shared capabilities come from small mixins, larger behaviour from collaborating objects.
- Values are immutable. Small value objects (
Data, frozen strings, symbols) can be passed around freely because nobody can change them underneath you.
Sandi Metz's book Practical Object-Oriented Design in Ruby is the classic, very readable treatment of these ideas, and its examples are in Ruby.
Common misunderstandings
Misconception
"attr_accessor for every instance variable is good practice." It makes every field changeable from anywhere, which defeats the point of the object guarding its own rules. Start with attr_reader (or nothing), and add operations named after what they do (register, cancel) rather than raw setters.
Misconception
"Class variables (@@count) are the way to store class-level data." A class variable is shared by the class and all its subclasses, so a subclass that assigns it changes the parent's value too, which surprises everyone. Prefer an instance variable on the class itself (set inside class << self or with self.class accessors) or a constant, and better still, avoid class-level mutable state.
Misconception
"Mixins are a substitute for inheritance everywhere." A module mixed into many classes couples all of them to its internals, and a class with ten modules is hard to follow. Mixins are excellent for small, general capabilities with a clear contract (Comparable, Enumerable). For larger pieces of behaviour, give the object a collaborator: a Report that has a formatter is clearer than one that is five modules.
Misconception
"private makes a method truly inaccessible." It prevents ordinary calls with an explicit receiver, nothing more: send(:registered?, "x") calls it anyway, as the next lesson shows. Visibility in Ruby communicates intent and keeps honest code honest; it is not a security boundary.
Exercises
1. Classes, modules and mixins
CoreComputationalWhat does this program print?
class Animal
def speak(sound = "...") = "The animal says #{sound}"
end
class Dog < Animal
def speak(sound = "woof") = super.upcase
end
puts Dog.new.speak
2. Classes, modules and mixins
CoreComputationalWhat does this print?
module A; end
module B; end
class C
include A
prepend B
end
p C.ancestors.first(3)
3. Classes, modules and mixins
CoreComputationalWhat does this program print?
class Base
@@n = 0
def self.add = @@n += 1
def self.n = @@n
end
class Child < Base; end
Base.add
Child.add
Child.add
puts Base.n
4. Classes, modules and mixins
Warm-upComputationalWhat does this print?
Pt = Data.define(:x, :y)
a = Pt.new(x: 1, y: 2)
b = a.with(y: 5)
p [a.y, b.y, a == Pt.new(1, 2)]
5. Classes, modules and mixins
CoreComputationalWithout the Version class, what does p %w[2.0.10 2.0.9].max print?
6. Classes, modules and mixins
CoreHumanA class defines <=> and includes Comparable. Which of these methods does Comparable itself give it? List them.
<, between?, clamp, ==, sort, each
7. Classes, modules and mixins
Warm-upHumanYou need a small value for an amount of money (cents and currency) that will be passed between many objects and used as a hash key. Which is the best fit in modern Ruby?
Further reading and resources
- Ruby docs: Modules and classesDefining classes and modules, visibility, and singleton classes.
- Ruby docs: Comparable
- Ruby docs: DataImmutable value objects, added in Ruby 3.2.
- Ruby docs: Struct
- The Ruby Style GuideThe community style guide, including its advice on classes and modules.