Classes and Inheritance

Classes and Inheritance in Ruby: --- Above the plate shop in an old shipyard there is a room called the mould loft: a single enormous flat floor, painted matt…


The Analogy: The Shipyard Mould Loft

Above the plate shop in an old shipyard there is a room called the mould loft: a single enormous flat floor, painted matt black and marked out in a grid. On that floor the loftsmen draw ship parts at full size -- not a scale drawing, but the actual curve of the actual frame, scribed into thin sheets of fibreboard. Those scribed sheets are the templates, and every piece of steel in the hull is cut against one. A cutter in the plate shop never measures a frame from a drawing. They lay the template on the plate, mark round it, and cut.

The important thing about the loft is what a template is not. It is not a frame. You cannot bolt it into a ship, and it carries no serial number, no station number, no record of which plate it came from. All of that belongs to the steel. The template holds only what every frame of that type has in common: the curve, the web depth, the bracket cut-out. The frame holds what is true of that one piece: F-104, station 4, web measured at 159mm against a nominal 160.

The loft also traces templates from templates. When the yard needs a shallow-draft variant, nobody redraws the frame; a loftsman lays a fresh sheet over the standard template, traces everything, and alters only the bilge radius. Whatever the variant does not change, it takes from the sheet underneath. And along the wall hang the detail stencils -- a bracket cut-out, a drain hole pattern, a weld-prep bevel -- which are not templates at all. They are laid over whichever template needs them. A stencil is not a kind of frame; it is a detail that many unrelated frames happen to share.

The loft fails in four ways, and each has a name in this lesson. A loftsman edits the master template so one awkward frame fits, and every frame cut afterwards inherits the error. A variant is traced from a variant traced from a variant, until nobody can say which sheet holds the bilge radius. Two stencils both define the bracket cut-out, and which one wins depends on the order they were laid down -- something the cutter cannot see at all. And a foreman needing the web depth measures the steel with a rule instead of asking the loft, so when the loft revises the nominal nothing downstream notices.


Syntax or Core Structure

A class is written with class, a constant name, and end. Inside it, def initialize is the method Ruby calls for you when someone writes ClassName.new; whatever new is handed gets passed straight through to initialize. Instance variables start with @ and belong to one object. attr_reader generates the getter methods you would otherwise write by hand; attr_accessor generates a getter and a setter. A subclass is written class Child < Parent, and super inside a method runs the version of that same method further up the chain.

# frame.rb -- one lofted template, several frames cut from it.

class Frame
  MIN_WEB_MM = 120

  attr_reader :serial, :length_mm, :web_mm
  attr_accessor :station

  def initialize(serial, length_mm, web_mm)
    @serial = serial
    @length_mm = length_mm
    @web_mm = web_mm
    @station = nil
  end

  def self.from_row(row)
    serial, length_mm, web_mm = row.split
    new(serial, length_mm.to_i, web_mm.to_i)
  end

  def area_mm2
    length_mm * web_mm
  end

  def compliant?
    web_mm >= MIN_WEB_MM
  end

  def kind
    "plain"
  end

  def to_s
    "#{kind} #{serial} #{length_mm}x#{web_mm}"
  end
end

class BilgeFrame < Frame
  attr_reader :radius_mm

  def initialize(serial, length_mm, web_mm, radius_mm)
    super(serial, length_mm, web_mm)
    @radius_mm = radius_mm
  end

  def kind
    "bilge"
  end

  def area_mm2
    super - radius_mm * radius_mm / 2
  end
end

plain = Frame.new("F-101", 2400, 180)
bilge = BilgeFrame.new("F-102", 2400, 180, 300)

puts plain
puts bilge
puts plain.area_mm2
puts bilge.area_mm2

plain.station = 14
puts "station #{plain.station}"

cut = Frame.from_row("F-103 1800 160")
puts cut
puts cut.area_mm2

puts "is_a?(Frame) #{bilge.is_a?(Frame)}"
puts "instance_of?(Frame) #{bilge.instance_of?(Frame)}"
puts "instance_of?(BilgeFrame) #{bilge.instance_of?(BilgeFrame)}"
puts "compliant? #{plain.compliant?}"
puts "superclass #{BilgeFrame.superclass}"
puts "min web #{Frame::MIN_WEB_MM}"
puts BilgeFrame.ancestors.take_while { |m| m != Object }.inspect

Output:

plain F-101 2400x180
bilge F-102 2400x180
432000
387000
station 14
plain F-103 1800x160
288000
is_a?(Frame) true
instance_of?(Frame) false
instance_of?(BilgeFrame) true
compliant? true
superclass Frame
min web 120
[BilgeFrame, Frame]

Several things in that output are worth stopping on. puts plain printed plain F-101 2400x180 without anyone calling a method, because puts asks its argument for to_s. puts bilge went through that same Frame#to_s -- the subclass never touches it -- yet printed bilge, because the #{kind} inside the inherited method resolved to BilgeFrame#kind. An inherited method still dispatches its own internal calls against the actual object. That is the whole of polymorphism in one line.

BilgeFrame#area_mm2 calls super, which runs Frame#area_mm2 for 432000, then subtracts 300 * 300 / 2 to give 387000. super is not a call to a differently named parent method; it is the same method name, one step further along the lookup chain. Frame.from_row is a class method -- defined with def self. -- so it hangs off the class object rather than off any frame, and inside it the bare new means Frame.new. attr_accessor :station is why plain.station = 14 works; without it that line raises NoMethodError, because assignment to an attribute is a call to station= and nothing else.

The three predicates separate two questions people conflate. is_a? asks whether the object answers to that type anywhere in its chain, so bilge.is_a?(Frame) is true. instance_of? asks whether the object's class is exactly that class, so bilge.instance_of?(Frame) is false. Almost every time you want one of these, you want is_a?. ancestors prints the lookup order itself; the take_while trims it at Object because everything past that point is Ruby's own furniture.


Technical Depth: Where State Lives And Where Methods Come From

Two questions answer most confusion about Ruby classes. When I write a variable, which object is holding it? And when I call a method, which definition runs? Both answers are entirely mechanical, and neither is what most people guess.

The Five Places State Can Live

Where it livesHow it is writtenWho can see itThe trap
instance variablean @ name inside an instance methodexactly one objectreading one that was never assigned gives nil instead of an error
class instance variablean @ name written at class body levelthe class object itself, not its subclasseseach subclass gets its own, starting at nil
class variablean @@ namethe class and every subclass, sharing one single slota subclass assigning to it changes the parent's value too
constanta capitalised nameanywhere, through the scope operatorit is constant only by convention; call freeze if you mean it
local variablea plain lowercase namethe one method call it was created init vanishes when the method returns, which is usually what you want

The two that trip people are the middle pair, because they look almost identical and behave nothing alike. A class instance variable is per-class: Frame and BilgeFrame each keep their own. A class variable is one storage location for the entire hierarchy, so a subclass incrementing a counter is incrementing the parent's.

Method Lookup Walks The Ancestors, In One Fixed Order

A module included in a class is inserted into the lookup chain just above the class itself. Include two modules and the one included last sits nearest the class, so it wins. This is the stencil problem from the loft.

module Stamped
  def stamp
    "#{self.class.name}:#{serial}"
  end

  def kind
    "stamped"
  end
end

module Drilled
  def kind
    "drilled"
  end
end

class Plate
  attr_reader :serial

  def initialize(serial)
    @serial = serial
  end

  def kind
    "plate"
  end
end

class StampedPlate < Plate
  include Stamped
  include Drilled
end

class QuietPlate < Plate
  include Stamped

  def kind
    "quiet"
  end
end

sp = StampedPlate.new("P-1")
qp = QuietPlate.new("P-2")

puts sp.stamp
puts sp.kind
puts qp.stamp
puts qp.kind
puts StampedPlate.ancestors.take_while { |m| m != Object }.inspect
puts StampedPlate.instance_method(:kind).owner
puts QuietPlate.instance_method(:kind).owner

Output:

StampedPlate:P-1
drilled
QuietPlate:P-2
quiet
[StampedPlate, Drilled, Stamped, Plate]
Drilled
QuietPlate

Stamped#stamp calls serial, a method the module does not define and knows nothing about. It works because the module was mixed into a class that happens to supply it. That is the real contract of a mixin: methods written against an interface the host class must provide. Comparable needs <=>; Enumerable needs each; Stamped needs serial. Nothing enforces it, which is why the requirement belongs in a comment at the top of the module.

sp.kind returned "drilled" even though Stamped defines kind and Plate defines it too. The chain printed the reason: Drilled came last in the source and therefore sits first. QuietPlate defines kind in the class body, and a method defined directly on the class always beats any included module. When you cannot work out where a method came from, instance_method(:name).owner tells you exactly, and ancestors tells you why.

super Goes To The Next Link, Not To The Parent Class

Because modules are in the chain, super does not mean "the superclass version". It means the next definition of this method name after the current one, whatever kind of thing owns it.

module Reinforced
  def area_mm2
    super + 5_000
  end
end

class HeavyFrame < Frame
  include Reinforced

  def area_mm2
    super * 2
  end
end

heavy = HeavyFrame.new("F-201", 1000, 200)
puts heavy.area_mm2
puts HeavyFrame.ancestors.take_while { |m| m != Object }.inspect

Output:

410000
[HeavyFrame, Reinforced, Frame]

Three definitions ran for one call. HeavyFrame#area_mm2 asked for super, which found Reinforced#area_mm2, which asked for super, which found Frame#area_mm2 and got 200000. The module added 5000, then the class doubled it: 205000 becomes 410000. Read from the bottom up.

One more distinction bites people who add a parameter to an old method. Bare super forwards the arguments the current method received; super() with empty parentheses forwards nothing, taking the parent's defaults instead. The two differ by two characters, and bare super is what you want almost always.


Real World Example: The Frame Schedule For One Hull Section

The loft issues a schedule: seven frames for one section of hull, three types among them. The plate shop needs, for each frame, the area of steel it consumes and the length of cut the flame table has to travel. Those two numbers are computed differently for each type -- a bilge frame loses a corner to its radius but gains cut length round the curve; a lightened frame loses area to its holes but gains a great deal of cut going round them. That difference is exactly what a subclass is for.

# frame_schedule.rb -- what the loft issued for one hull section.

class Frame
  MIN_WEB_MM = 120

  attr_reader :serial, :station, :length_mm, :web_mm

  def initialize(serial, station, length_mm, web_mm)
    @serial = serial
    @station = station
    @length_mm = length_mm
    @web_mm = web_mm
  end

  def kind
    "plain"
  end

  def area_mm2
    length_mm * web_mm
  end

  def cut_mm
    2 * (length_mm + web_mm)
  end

  def compliant?
    web_mm >= MIN_WEB_MM
  end

  def to_s
    format("%-6s st%-3d %-6s %4d x %3d", serial, station, kind, length_mm, web_mm)
  end
end

class BilgeFrame < Frame
  attr_reader :radius_mm

  def initialize(serial, station, length_mm, web_mm, radius_mm)
    super(serial, station, length_mm, web_mm)
    @radius_mm = radius_mm
  end

  def kind
    "bilge"
  end

  def area_mm2
    super - radius_mm * radius_mm / 2
  end

  def cut_mm
    super + radius_mm
  end
end

class LightFrame < Frame
  HOLE_MM = 80

  attr_reader :holes

  def initialize(serial, station, length_mm, web_mm, holes)
    super(serial, station, length_mm, web_mm)
    @holes = holes
  end

  def kind
    "light"
  end

  def area_mm2
    super - holes * HOLE_MM * HOLE_MM
  end

  def cut_mm
    super + holes * 4 * HOLE_MM
  end
end

SCHEDULE = <<~ROWS
  F-101 1 plain 2400 180
  F-102 2 bilge 2400 180 300
  F-103 3 light 2400 180 4
  F-104 4 plain 1800 160
  F-105 5 bilge 1800 160 240
  F-106 6 light 1800 160 3
  F-107 7 plain 1200 110
ROWS

def build(row)
  serial, station, kind, length_mm, web_mm, extra = row.split
  args = [serial, station.to_i, length_mm.to_i, web_mm.to_i]

  case kind
  when "bilge" then BilgeFrame.new(*args, extra.to_i)
  when "light" then LightFrame.new(*args, extra.to_i)
  else Frame.new(*args)
  end
end

frames = SCHEDULE.lines.map { |row| build(row) }
puts "frames: #{frames.size}"

frames.each do |f|
  puts format("  %s  area %7d  cut %5d", f, f.area_mm2, f.cut_mm)
end

by_kind = frames.group_by(&:kind)
by_kind.keys.sort.each do |kind|
  batch = by_kind[kind]
  puts format("  %-6s n=%d  area %7d  cut %5d",
              kind, batch.size, batch.sum(&:area_mm2), batch.sum(&:cut_mm))
end

flagged = frames.reject(&:compliant?)
puts "below the #{Frame::MIN_WEB_MM}mm minimum: #{flagged.size}"
flagged.each { |f| puts "  #{f.serial} web #{f.web_mm}mm" }

puts format("total area %d mm2, total cut %d mm",
            frames.sum(&:area_mm2), frames.sum(&:cut_mm))
puts "classes used: #{frames.map { |f| f.class.name }.uniq.sort.inspect}"
puts "every frame is a Frame: #{frames.all?(Frame)}"

Output:

frames: 7
  F-101  st1   plain  2400 x 180  area  432000  cut  5160
  F-102  st2   bilge  2400 x 180  area  387000  cut  5460
  F-103  st3   light  2400 x 180  area  406400  cut  6440
  F-104  st4   plain  1800 x 160  area  288000  cut  3920
  F-105  st5   bilge  1800 x 160  area  259200  cut  4160
  F-106  st6   light  1800 x 160  area  268800  cut  4880
  F-107  st7   plain  1200 x 110  area  132000  cut  2620
  bilge  n=2  area  646200  cut  9620
  light  n=2  area  675200  cut 11320
  plain  n=3  area  852000  cut 11700
below the 120mm minimum: 1
  F-107 web 110mm
total area 2173400 mm2, total cut 32640 mm
classes used: ["BilgeFrame", "Frame", "LightFrame"]
every frame is a Frame: true

The seven detail lines came from one format call with one %s for the whole frame, and each printed a different type name and a different pair of figures. Nothing in that loop tests what kind of frame it has. f.area_mm2 on F-102 ran BilgeFrame#area_mm2, which took 432000 from super and subtracted 300 * 300 / 2; on F-103 it ran LightFrame#area_mm2 and subtracted four 80mm squares, 25600 in all. The cut_mm figures moved the other way: F-103's 6440 is the plain 5160 plus 4 * 4 * 80, because every hole adds its own perimeter to the flame table's journey. Both subclasses got there by calling super and adjusting, so neither repeats the base arithmetic.

The grouping and the totals are pure Enumerable and never learn that subclasses exist. group_by(&:kind) keys on whatever each object says it is, and keys.sort makes the group lines alphabetical rather than first-seen, so the report is a function of the data and not of the heredoc's row order. The figures reconcile: 646200 plus 675200 plus 852000 is 2173400, and 9620 plus 11320 plus 11700 is 32640, matching both grand totals exactly.

reject(&:compliant?) caught F-107, whose 110mm web is under the minimum; that check lives once, in Frame, and all three types inherit it. frames.all?(Frame) is true because all? given a class argument tests with ===, which for a class means is_a?. And classes used proves the schedule really did instantiate three classes rather than one class with a type field.

Now the limits, and there is a serious one. build is a case on a String that names every subclass, so the hierarchy is open to extension but the only place objects are created is not: adding a BracketFrame means editing build, and nothing will remind you. Worse, the else branch is a silent catch-all. Write blige instead of bilge and you get a plain Frame -- the radius is parsed into extra, then dropped, and the frame is reported at 432000mm2 instead of 387000 with no warning anywhere. The polymorphism the three classes were designed for is defeated at the single point where objects come into existence. A registry keyed on the string, or a raise in the else, would fix it; the case fixes nothing and hides the error.

Three narrower flaws. MIN_WEB_MM is referenced inside Frame#compliant?, and Ruby resolves constants lexically rather than through the receiver -- so a subclass defining its own MIN_WEB_MM is still checked against the parent's, and the override looks like it did nothing. LightFrame inherits compliant? untouched, so F-103 passes on web depth while four 80mm holes have removed 25600mm2 from that web. And BilgeFrame#area_mm2 divides by 2 with integer division, so an odd radius quietly loses half a square millimetre.


Common Mistakes

  1. Mistyping an instance variable and getting nil instead of an error. @web_mm and @webb_mm are both legal; the second has simply never been assigned, and Ruby hands back nil without a murmur. The failure surfaces later as an undefined method on nil, in a different method. This is why attr_reader plus the bare method name is worth using even inside the class: a mistyped method call raises NoMethodError at the point of the mistake.
  1. Forgetting super in a subclass initialize. Defining initialize in a subclass replaces the parent's entirely -- it does not extend it. Every instance variable the parent set is now nil, and because of mistake 1 nothing complains until something does arithmetic on one.
  1. Reaching for attr_accessor by default. A writer is a decision to let anything, anywhere, change that value at any time. Frame exposes station for writing because frames genuinely get reassigned on the shop floor, and web_mm read-only because a cut frame's web depth is a measured fact.
  1. Using inheritance to share code rather than to share an interface. BilgeFrame < Frame is honest: a bilge frame answers every message a frame answers and can stand in for one anywhere. A class that inherits merely because the parent contains two useful methods drags in the parent's entire surface and locks you into its future. If "a Y is a kind of X" sounds wrong out loud, use a module or hold an instance instead.
  1. Depending on module include order without knowing you are. Two modules defining the same method name is not an error, not a warning, and not visible at the call site. The last include wins. If two mixins overlap even slightly, print ancestors once and write down what you found.
  1. Defining == and stopping there. == governs a == b. It does not govern uniq, tally, group_by or Hash lookup, all of which use hash and eql?. A value object with only == will compare equal in an if and then appear twice in a uniq. Define all three, keep them consistent, and never touch equal?.
  1. Using @@ class variables for state a subclass should own. A class variable is one slot shared by the whole hierarchy, so a subclass writing to it overwrites the parent's value and every sibling's view of it. If each class needs its own counter or registry, use a class instance variable with a class-level attr_accessor.
  1. Expecting a constant to resolve through the receiver. Frame#compliant? refers to MIN_WEB_MM, which Ruby resolves in the lexical scope where the method was written -- always Frame::MIN_WEB_MM, whatever class the object actually is. A subclass can define its own and the inherited method will ignore it. Wrap the value in a method the subclass can override, and constants stop pretending to be polymorphic.
  1. Reopening a core class to add one convenience method. class String with your own method in it works everywhere in the process, including inside every gem you did not write. When two libraries do this to the same name, the one loaded second wins and the failure is unattributable. This is the loftsman editing the master template so one awkward frame fits.

Best Practices

  • Default to attr_reader and expose writers one at a time. Every writer you do not create is a class of bug you cannot have. When a value must change, consider a named method saying what the change means -- reassign_to(station) -- rather than a bare setter.
  • Keep initialize to assignment and validation. No file reads, no network calls, no computation that might fail. If building an object needs work, put that work in a class method like Frame.from_row.
  • Prefer composition, and reserve inheritance for a real is a. Inheritance is the tightest coupling Ruby offers: the subclass depends on the parent's methods, its instance variables, and its future. If you find yourself four levels deep, one of them is holding data that should have been a separate object.
  • Ask is_a?, not instance_of? or a class comparison. Class equality rejects every subclass, which means it rejects exactly the objects your hierarchy was built to let through. Better still, ask respond_to? or just send the message.
  • Give every class a to_s. It costs three lines and pays for itself the first time you put an object in a string. Add inspect when the debugger view should differ, and keep both free of anything that could raise.
  • State a module's requirements in the module. Enumerable needs each, Comparable needs <=>, and Stamped needs serial. Ruby will not check, so write the requirement in a comment on the first line.
  • Treat value objects as values. Define ==, eql? and hash together, return new objects rather than mutating in place, and freeze in initialize if the object never changes. A frozen value object can be shared without a defensive copy.
  • When a method surprises you, print the chain. ancestors shows the lookup order and instance_method(:name).owner shows the winner. Thirty seconds with those two beats an afternoon of reading class bodies.

Practice Exercises

  1. Close the factory. Add a BracketFrame to frame_schedule.rb: it takes a plain frame's dimensions plus a throat_mm, subtracts throat_mm squared over two from the area, and adds three times throat_mm to the cut. Then replace the case in build with a Hash registry mapping the kind string to the class, and raise ArgumentError on an unknown kind. Prove the fix with a deliberate blige row.
  1. Make the minimum polymorphic. Fix mistake 8 in the running code. Replace MIN_WEB_MM inside compliant? with a call to a min_web_mm method returning 120 in Frame, then override it in LightFrame to account for the area its holes remove -- so a lightened frame is judged on the web it actually has left. Print every frame's compliant? before and after and confirm F-103 changes verdict.
  1. A batch that behaves like a collection. Write a Batch class holding an Array of frames. include Enumerable and define each so map, select, sum and sort_by all work. Then include Comparable and define <=> on total area so two batches compare directly. Print batch.sum(&:cut_mm), batch.max_by(&:area_mm2), and one batch > another. Do not define map or > yourself; if you needed to, your each or <=> is wrong.
  1. Trace a collision on purpose. Write two modules that both define label, include them in one class, print the result and ancestors, then swap the two include lines and print again. Then define label in the class body and print a third time. Explain in two sentences, citing the ancestors output, why the class definition wins over both modules and why the second include beats the first.