Ruby Inheritance
Inheritance lets one class build on another. The new class (the subclass) gets every method of the existing class (the superclass) and can add new methods or change existing ones. Ruby supports single inheritance: each class has exactly one superclass.
The < operator
class Vehicle
def initialize(wheels)
@wheels = wheels
end
def describe
"A vehicle with #{@wheels} wheels"
end
def honk
"Beep!"
end
end
class Bicycle < Vehicle
def initialize
super(2)
end
def ring_bell
"Ring ring!"
end
end
bike = Bicycle.new
puts bike.describe
puts bike.honk
puts bike.ring_bell
p Bicycle.superclass
p bike.is_a?(Vehicle)A vehicle with 2 wheels
Beep!
Ring ring!
Vehicle
true
Bicycle inherits describe and honk, adds ring_bell, and passes 2 to the parent's initialize with super.
Overriding methods
A subclass can redefine a method. Ruby looks for a method in the object's own class first, then in its superclass, and so on:
class Animal
attr_reader :name
def initialize(name)
@name = name
end
def speak
"..."
end
def introduce
"#{name} says #{speak}"
end
end
class Cat < Animal
def speak = "Meow"
end
class Cow < Animal
def speak = "Moo"
end
[Cat.new("Tiger"), Cow.new("Bella"), Animal.new("Mystery")].each do |a|
puts a.introduce
endTiger says Meow
Bella says Moo
Mystery says ...
introduce is written once in Animal, but each call to speak uses the version of the actual object's class. This is polymorphism.
super
super calls the same method in the parent class. There are three forms:
| Form | Passes to the parent |
|---|---|
super |
the same arguments the current method received |
super(a, b) |
exactly the arguments you list |
super() |
no arguments at all |
class Employee
attr_reader :name, :salary
def initialize(name, salary)
@name = name
@salary = salary
end
def summary
"#{name} earns #{salary}"
end
end
class Manager < Employee
def initialize(name, salary, team)
super(name, salary)
@team = team
end
def summary
super + " and leads #{@team.size} people"
end
end
m = Manager.new("Olu", 5200, ["Ann", "Raj", "Li"])
puts m.summary
puts Employee.new("Raj", 3900).summaryOlu earns 5200 and leads 3 people
Raj earns 3900
Using super inside summary lets you extend the parent's result instead of copying its code.
Note: A subclass that defines its own
initializemust callsuperif the parent's setup (like setting@name) should still happen.
The ancestor chain
Every class ultimately inherits from Object (and BasicObject). ancestors shows the lookup order Ruby uses to find a method:
class Shape; end
class Polygon < Shape; end
class Triangle < Polygon; end
p Triangle.ancestors.take(4)
p Triangle.superclass.superclass
p Triangle.new.is_a?(Shape)
p Triangle.new.instance_of?(Shape)
p Triangle < Shape[Triangle, Polygon, Shape, Object]
Shape
true
false
true
Template method pattern
A common design: the parent defines the overall algorithm, and subclasses fill in the specific steps:
class Report
def render
[header, body, footer].join("\n")
end
def header = "== #{title} =="
def footer = "-- end --"
end
class SalesReport < Report
def title = "Sales"
def body = "Total: 1200"
end
class StockReport < Report
def title = "Stock"
def body = "Items: 87"
def footer = "-- checked daily --"
end
puts SalesReport.new.render
puts StockReport.new.render== Sales ==
Total: 1200
-- end --
== Stock ==
Items: 87
-- checked daily --
Inheriting from built-in classes
You can subclass core classes, including exceptions — which is how custom errors are made:
class OutOfStockError < StandardError
def initialize(item)
super("#{item} is out of stock")
end
end
begin
raise OutOfStockError, "Blue mug"
rescue OutOfStockError => e
puts e.message
p e.class.ancestors.take(3)
endBlue mug is out of stock
[OutOfStockError, StandardError, Exception]
When not to inherit
Inheritance expresses an "is a" relationship: a Cat is an Animal. If the relationship is "has a" or "can do", prefer composition (an object holding another) or modules (next lesson). Deep inheritance trees are hard to change.
Test yourself
How do you declare that Car inherits from Vehicle?
class Car extends Vehicleclass Car < Vehicleclass Car : Vehicleclass Car(Vehicle)
What does super without parentheses pass to the parent method?
- No arguments
- The same arguments the current method received
- Only the first argument
self
How many superclasses can a Ruby class have?
- Zero
- Exactly one (except BasicObject)
- Any number
- Two