Thuta Learning
Ruby
AdvancedProgrammingBeginner

Inheritance

RubyLesson 2030 min

What you'll walk away with

  • Declare a subclass with class Child < Parent and explain Ruby's single-inheritance rule
  • Read Car.ancestors to predict which method will run
  • Say what super(args), bare super and super() each pass to the parent
  • Write abstract-style methods with NotImplementedError and explain why a bare rescue misses them
  • Decide when composition or a mixin fits better than a subclass

Explain it simply

Inheritance in plain language

Inheritance lets a new class start life with the abilities of an existing one. In Ruby you write class Car < Vehicle, and from that moment every Car can do everything a Vehicle can, plus whatever Car adds or changes on its own. The shared code lives in one place, the parent class, and each child only describes how it differs.

A quick test tells you whether inheritance fits: say "a Car is a Vehicle" out loud. If the sentence sounds natural it is an is-a relationship and a subclass is a good tool. If it sounds odd, like "a Car is an Engine", the car merely has an engine, and a field holding another object is the better design.

Problem → Why → Solution

The problem: growing code by copying a class

A small garage app starts with a Car class, and a week later someone needs a Truck. The quick move is to copy Car and rename it. Now name, the constructor and start_engine exist twice. When the start-up message changes, both copies must be edited, and sooner or later someone edits only one.

Copying also hides the relationship. Ruby will not stop you from asking whether a Car is a Truck, and nothing in the code says that both are vehicles, so you cannot write a check like vehicle.is_a?(Vehicle) or ask which methods all vehicles share. The duplication is the visible cost; the missing common ancestor is the hidden one.

garage_copy.rb
class Car
  attr_reader :name

  def initialize(name)
    @name = name
  end

  def start_engine
    "#{name}: engine started"
  end
end

class Truck               # a pasted copy of Car with a new name
  attr_reader :name

  def initialize(name)
    @name = name
  end

  def start_engine
    "#{name}: engine started"
  end
end

p Car.new("Coupe").is_a?(Truck)    # false, and no shared type exists

Shared behaviour belongs in one parent

A parent class gives the shared code a single home. Change start_engine there and every vehicle changes with it. It also gives the objects a shared type, so is_a?(Vehicle) is true for cars and trucks alike, and a method that needs "any vehicle" can accept both.

Core concept: superclass, method lookup and super

class Car < Vehicle declares Vehicle as the superclass of Car. Ruby has single inheritance: a class has exactly one superclass, and if you write none it is Object, whose own parent is BasicObject. A Car object has everything the Car class defines, and also every public and private instance method of Vehicle, Object and Kernel, which is why puts, inspect and to_s work on objects you never taught them to.

When you call car.start_engine Ruby performs method lookup. It begins in the object's class and walks up the ancestor chain, one class at a time, running the first method with that name it finds. Car.ancestors prints that chain: [Car, Vehicle, Object, Kernel, BasicObject]. Overriding is nothing more than defining a method with the same name lower in the chain, so it is found first and the parent's version is hidden.

text
Method lookup for car.start_engine
----------------------------------
car.start_engine
      |
      v
   +-----+  not here   +---------+  found: run it
   | Car | ----------> | Vehicle | ---------------> "Coupe: engine started"
   +-----+             +---------+
                            | (only if still missing)
                            v
                  Object -> Kernel -> BasicObject -> NoMethodError

super continues the lookup from the next class in the chain. It has three forms. super(a, b) passes exactly the arguments you list. A bare super, with no parentheses, forwards the current values of the method's own parameters, including keyword arguments and the block. super() with empty parentheses passes nothing at all. The difference matters most in initialize: the parent's setup does not run on its own, so a child that defines initialize must call super, otherwise the parent's instance variables are never set.

Instance variables belong to the object, not to a class, so a method inherited from Vehicle simply reads whatever @name the object has. Private methods are inherited too, and a subclass can call them without a receiver, unlike in some other languages. Class methods defined with def self.name are inherited as well, and is_a? answers true for the class itself and all its ancestors while instance_of? answers true for the exact class only.

Mental model: a chain of classes
  1. Call car.describe
  2. Look in Car first
  3. Not there? Climb to Vehicle
  4. Keep climbing to Object, BasicObject
  5. Found: run it. None: NoMethodError

Overriding and calling super both work along this chain, so once you can read ancestors you can predict what runs.

General pattern

ruby
class Parent
  def initialize(a) = @a = a
  def action = "parent"
end

class Child < Parent
  def initialize(a, b)
    super(a)               # run Parent#initialize
    @b = b
  end
  def action = super + " and child"
end

class Child < Parent is the inheritance. Child's initialize runs the parent's setup first with super(a) and then sets its own field. action takes the result of super and adds to it, so it extends the parent's behaviour instead of replacing it.

Example: Car and Motorbike extending Vehicle

Vehicle supplies name, wheels and two methods. Car fixes the wheel count at 4, adds a door count and extends describe. Motorbike supplies 2 wheels and extends start_engine only. Notice that Car never writes start_engine at all; it comes along the chain.

vehicles.rb
class Vehicle
  attr_reader :name, :wheels

  def initialize(name, wheels)
    @name = name
    @wheels = wheels
  end

  def describe
    "#{name} has #{wheels} wheels"
  end

  def start_engine
    "#{name}: engine started"
  end
end

class Car < Vehicle
  def initialize(name, doors)
    super(name, 4)
    @doors = doors
  end

  def describe
    "#{super} and #{@doors} doors"
  end
end

class Motorbike < Vehicle
  def initialize(name)
    super(name, 2)
  end

  def start_engine
    "#{super} with a kick"
  end
end

car = Car.new("Coupe", 2)
bike = Motorbike.new("Vespa")

puts car.describe
puts bike.describe
puts car.start_engine
puts bike.start_engine
p Car.ancestors
puts car.is_a?(Vehicle)
puts car.instance_of?(Vehicle)
puts Car.superclass

Code breakdown

  1. Subclass lineclass Car < Vehicle

    The < makes Vehicle the superclass of Car. Every object made by Car.new finds Vehicle's methods by walking the chain.

  2. Explicit supersuper(name, 4)

    Car's initialize takes name and doors, but Vehicle#initialize needs name and wheels. So it passes super(name, 4) explicitly and sets @doors afterwards.

  3. Extending with super"#{super} and #{@doors} doors"

    The bare super inside the string calls Vehicle#describe and uses its result, then appends the door count, so the parent's format is extended without being rewritten.

  4. Partial override"#{super} with a kick"

    Motorbike's start_engine takes Vehicle's text and adds a suffix. This kind of override keeps the parent's behaviour and builds on it.

  5. Reading the chainp Car.ancestors

    It prints [Car, Vehicle, Object, Kernel, BasicObject]. Lookup goes left to right, and the first match runs.

  6. is_a? versus instance_of?puts car.instance_of?(Vehicle)

    is_a?(Vehicle) is true, but instance_of?(Vehicle) is false because the car's exact class is Car. Most of the time is_a? is the check you want.

You should see
Coupe has 4 wheels and 2 doors
Vespa has 2 wheels
Coupe: engine started
Vespa: engine started with a kick
[Car, Vehicle, Object, Kernel, BasicObject]
true
false
Vehicle
How Ruby resolves bike.start_engine
  1. bike.start_engine is called
  2. Ruby checks Motorbike for start_engine
  3. Found: it runs, and on reaching super it climbs to Vehicle
  4. Vehicle#start_engine's result is taken and " with a kick" is appended

Found in some class on the chain

That method runs, and super can reach the next one

Not found anywhere on the chain

NoMethodError

super in detail: bare super, super() and a forgotten super

The three forms of super behave differently, and the differences show up as quiet bugs. In the code below, WithBareSuper reassigns name and then calls bare super, so the parent receives the upcased value: bare super forwards the current values of the parameters, not the ones the caller originally passed. WithEmptyParens calls super() and the parent falls back to its own defaults. Broken shows the error you get when the parent needs an argument and super() supplies none, and Forgetful shows the quieter failure of leaving super out of initialize altogether: nothing complains, but the parent's instance variables are never set.

super_forms.rb
class Parent
  def greet(name = "world", punct: "!")
    "hello #{name}#{punct}"
  end
end

class WithBareSuper < Parent
  def greet(name = "kid", punct: "?")
    name = name.upcase
    super                     # forwards the CURRENT name and punct
  end
end

class WithEmptyParens < Parent
  def greet(name = "kid", punct: "?")
    super()                   # forwards nothing: Parent's defaults apply
  end
end

puts WithBareSuper.new.greet                       # hello KID?
puts WithBareSuper.new.greet("amy", punct: ".")    # hello AMY.
puts WithEmptyParens.new.greet("amy", punct: ".")  # hello world!

class Base
  def initialize(id)
    @id = id
  end
end

class Broken < Base
  def initialize(id, label)
    super()                   # Base needs one argument
  end
end

begin
  Broken.new(1, "x")
rescue ArgumentError => e
  puts e.message              # wrong number of arguments (given 0, expected 1)
end

class Fixed < Base
  def initialize(id, label)
    super(id)
    @label = label
  end
end
p Fixed.new(1, "x").instance_variables      # [:@id, :@label]

class Forgetful < Base
  def initialize(id, label)
    @label = label            # forgot super
  end
end
p Forgetful.new(1, "x").instance_variables  # [:@label]

Abstract-style methods with NotImplementedError

Ruby has no abstract keyword. By convention a parent class defines a method that raises NotImplementedError, and each subclass overrides it. The describe method of Shape below is a template method: it calls area, and each subclass's version of area runs. NotImplementedError inherits from ScriptError, not StandardError, so a bare rescue => e does not catch it. That is intentional, because a missing implementation is a programming mistake, and the second half of the code proves it.

abstract_shape.rb
class Shape
  def area
    raise NotImplementedError, "#{self.class} must implement area"
  end

  def describe
    "#{self.class.name.downcase} with area #{area}"
  end
end

class Square < Shape
  def initialize(side)
    @side = side
  end

  def area = @side * @side
end

class Blob < Shape; end

puts Square.new(3).describe        # square with area 9

begin
  Blob.new.describe
rescue NotImplementedError => e
  puts "#{e.class}: #{e.message}"  # NotImplementedError: Blob must implement area
end

p NotImplementedError.ancestors.first(3)  # [NotImplementedError, ScriptError, Exception]

begin
  begin
    Blob.new.area
  rescue => e
    puts "bare rescue caught it"
  end
rescue NotImplementedError
  puts "only an explicit rescue NotImplementedError catches it"
end

Inheritance or something else?

A subclass is a promise that is hard to take back: the child must work anywhere the parent does, and it keeps every one of the parent's methods. Extending Array to build a Stack gives you push and pop, but it also hands out unshift and every other method that breaks stack discipline. The table shows what to choose in each situation.

SituationBetter tool
A Manager is an Employee and shares most behaviourSubclass
Unrelated classes need the same helper methodsModule mixin (next lesson)
A Car has an EngineA field holding another object (composition)
You want array-like behaviour but fewer methodsWrap an Array in an instance variable and write your own methods
stack_from_array.rb
class Stack < Array
  def peek = last
end

stack = Stack.new
stack.push(1)
stack.push(2)
p stack.peek        # 2

stack.unshift(99)   # inherited from Array: slips in at the bottom
p stack             # [99, 1, 2]

In real projects

Where this shows up in real projects

Rails apps are full of class relationships: class ApplicationController < ActionController::Base, class Post < ApplicationRecord, and a Minitest test is class CartTest < Minitest::Test. Gems define error classes for their library, such as class PaymentError < StandardError, so callers can rescue exactly those. Frameworks hand you hooks to override and often expect super in places like initialize, because skipping it loses the framework's own setup.

The deeper such a hierarchy gets, the harder it is to see where a method comes from, which is why experienced developers keep chains to two or three levels. When debugging, obj.method(:name).owner tells you which class supplied the method and .super_method.owner shows the version it hides, so together with ancestors you can see the whole picture.

Common mistakes

Common mistakes

1. Not calling super inside initialize

If you write a child initialize and do not call super, the parent's initialize is skipped. Nothing raises; instance variables such as @wheels simply stay nil, and later describe returns nonsense like "Oops has wheels". Make calling super(...) the first line of a child initialize a habit.

2. Using super and super() interchangeably

Bare super forwards all the current parameters, while super() forwards none. A bare super inside a child initialize(id, label) sends two arguments, which raises ArgumentError if the parent accepts only one; super() in the same place sends none and fails with "wrong number of arguments (given 0, expected 1)". Spell out what you mean, as in super(id).

3. Subclassing just to reuse code when it is not is-a

With class Stack < Array, Stack inherits every Array method, so unshift can slip an item in at the bottom. Mistakes like this let outside code break your rules; wrapping an Array in an instance variable and exposing only push, pop and peek is safer.

4. Overriding and losing the parent's work

A subclass that replaces a method doing logging or validation, without calling super, silently drops that work. When you mean to extend, call super; when you truly mean to replace, say so in a comment.

Best practices

Best practices

  • Keep hierarchies shallow, ideally two or three levels.
  • Write code against the shared interface (methods like describe and area), not against individual subclasses.
  • Use super to extend, so a subclass never loses the parent's work by accident.
  • Raise NotImplementedError with a clear message such as "#{self.class} must implement area" in abstract-style methods.
  • If the relationship is not is-a, choose composition or a module.

Mini challenge

Mini challenge: a Shape hierarchy

Write Shape as a parent with an abstract-style area, then add Circle and Rectangle as subclasses. Also try a Blob that never implements area.

  • Shape#initialize(name) remembers the name, and Shape#area raises NotImplementedError with "#{self.class} must implement area"
  • Shape#describe returns "<name> area=<area rounded to 2 places>"
  • Circle(radius) and Rectangle(width, height) call the parent with super("Circle") and so on, and override area
  • Call describe on Blob < Shape, rescue NotImplementedError, and print the class and message
shapes.rb
class Shape
  def initialize(name)
    # TODO: remember the name
  end

  def area
    # TODO: signal that subclasses must implement this
  end

  def describe
    # TODO: "<name> area=<area rounded to 2 places>"
  end
end

# TODO: class Circle < Shape (radius), class Rectangle < Shape (width, height)
# TODO: class Blob < Shape that never defines area
# TODO: print both shapes, then call describe on a Blob and rescue the error

Expected: Expected output: Circle area=78.54 Rectangle area=12.0 NotImplementedError: Blob must implement area

Show hint

Circle's area is Math::PI * @radius**2. Call super("Circle") first inside the subclass initialize and then set @radius. Give Blob an initialize that calls super("Blob"), otherwise Shape#initialize will complain about the missing argument.

Show solution
shapes.rb
class Shape
  attr_reader :name

  def initialize(name)
    @name = name
  end

  def area
    raise NotImplementedError, "#{self.class} must implement area"
  end

  def describe
    "#{name} area=#{area.round(2)}"
  end
end

class Circle < Shape
  def initialize(radius)
    super("Circle")
    @radius = radius
  end

  def area
    Math::PI * @radius**2
  end
end

class Rectangle < Shape
  def initialize(width, height)
    super("Rectangle")
    @width = width
    @height = height
  end

  def area
    @width * @height
  end
end

class Blob < Shape
  def initialize
    super("Blob")
  end
end

puts Circle.new(5).describe
puts Rectangle.new(3, 4.0).describe

begin
  Blob.new.describe
rescue NotImplementedError => e
  puts "#{e.class}: #{e.message}"
end

Quick quiz 1 / 3

Animal#initialize sets @name. If class Cat < Animal defines def initialize(name, lives); @lives = lives; end, what does Cat.new("Tom", 9).name return?

Quick quiz 2 / 3

Given class A; def hi(x = 1) = "A#{x}"; end and class B < A; def hi(x = 2) = super(); end, what does B.new.hi(5) return?

Quick quiz 3 / 3

Blob.new.area raises NotImplementedError. Which handler catches it?

What to remember

  • class Child < Parent makes Child a subclass of Parent; a Ruby class has one superclass, and Child.ancestors shows the lookup chain.
  • Ruby walks the chain from the receiver's class and runs the first match; overriding means defining the same name lower in the chain.
  • super(a) passes what you list, bare super passes the parameters' current values and super() passes nothing; never forget super in a child initialize.
  • NotImplementedError is a ScriptError, so a bare rescue misses it; when the relationship is not is-a, choose composition or a module over a subclass.

Official Ruby Documentation — Ruby Documentation

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Inheritance | Thuta Learning