Ruby inheritance
Ruby inheritance explains the < symbol in class Article < ApplicationRecord. The lessons build a BankAccount class and subclasses such as SavingsAccount and OverdraftAccount. They cover inheriting methods, overriding a parent method and calling super in its three forms. They show how .ancestors lists the method lookup path and how superclass confirms the chain on the Catalog::Course model. ApplicationRecord is read as a middle link marked with primary_abstract_class. The course closes with when inheritance fits, when composition fits better, and a small hierarchy combining everything.
What you'll learn
- ✓How class Child < Parent makes a parent's methods available on a subclass
- ✓Overriding a parent method and how Ruby picks the child's version first
- ✓The differences between bare super, super(args) and super()
- ✓Reading the lookup path with .ancestors and the chain with superclass
- ✓Why ApplicationRecord sits between ActiveRecord::Base and each model
- ✓When to use inheritance and when to use composition
class Child < Parent
This line has appeared since the first Rails core course. The Ruby classes & initialize course explained class, initialize and attr_accessor. That covers every part of this line except one character: <. The symbol means inheritance: Article inherits from ApplicationRecord. This course explains what…
Read the full lesson free →Curriculum
7 lessonsclass Child < Parent
An empty SavingsAccount < BankAccount inherits every BankAccount method, and is_a? confirms it is a kind of BankAccount.
Overriding a parent method
OverdraftAccount redefines withdraw, and Ruby runs the child's version first while other inherited methods stay unchanged.
Calling super
super calls the parent's version of a method, and bare super, super(args) and super() pass arguments differently.
The ancestors chain
.ancestors returns the lookup path Ruby follows, while superclass shows the inheritance chain of Catalog::Course.
ApplicationRecord is inheritance too
ApplicationRecord inherits from ActiveRecord::Base and acts as a shared middle link, marked by primary_abstract_class with no table.
Choosing inheritance wisely
Use < when the child is a kind of the parent, prefer composition for has-a relationships, and avoid deep chains.
Putting it together: a small hierarchy
A SavingsAccount hierarchy combines inheritance, overriding, super and the ancestors path through a minimum-balance withdrawal rule.