Ruby Inheritance and Method Lookup — Complete Beginner Guide
Learning Objectives
- Create subclasses using the less-than symbol for inheritance
- Override parent methods in child classes
- Call parent implementations with super
- Trace Ruby's method lookup chain
- Decide when inheritance fits and when composition fits better
What Is Inheritance
Inheritance lets a class reuse and extend another class. The original class is the superclass, and the new class is the subclass. Subclasses inherit instance methods, so shared behavior lives in one place.
class Animal
def speak
puts "Some sound"
end
end
class Dog < Animal
end
rex = Dog.new
rex.speak
Dog inherits speak from Animal without redefining it. The less-than symbol reads as "inherits from."
Adding Subclass Behavior
Subclasses can introduce entirely new methods:
class Animal
def initialize(name)
@name = name
end
end
class Dog < Animal
def fetch(item)
puts "#{@name} fetches the #{item}"
end
end
rex = Dog.new("Rex")
rex.fetch("ball")
The subclass focuses on dog-specific behavior while shared setup stays in the parent.
Overriding Methods
A subclass method with the same name as a parent method takes priority.
class Animal
def speak
puts "Generic animal sound"
end
end
class Cat < Animal
def speak
puts "Meow"
end
end
cat = Cat.new
cat.speak
Cat's definition wins because Ruby looks at the object's actual class first.
Calling the Parent with super
Sometimes you want parent behavior plus your own additions. super invokes the same-named method from the superclass.
class Animal
def initialize(name)
@name = name
end
end
class Dog < Animal
def initialize(name, breed)
super(name)
@breed = breed
end
def intro
puts "#{@name} is a #{@breed}"
end
end
rex = Dog.new("Rex", "Beagle")
rex.intro
super(name) reuses the parent's initialization for shared attributes while the child handles its extras.
super with no arguments
Calling super without parentheses passes the current method's arguments automatically, which keeps wrappers concise.
The Method Lookup Chain
When you call a method, Ruby searches in a specific order:
- The object's singleton class, if any
- The object's class
- Superclasses, moving upward
- Included modules along the way
- BasicObject at the root
If nothing matches, Ruby raises a no-method error. Understanding this chain explains why some methods are available on your objects and others are not.
Checking ancestors
class Animal; end
class Dog < Animal; end
puts Dog.ancestors.inspect
ancestors prints the lookup order, including any modules mixed into the hierarchy. Keep this tool handy when debugging surprising method availability.
Inheritance hierarchies
You can stack multiple levels:
class Shape
def describe
puts "I am a shape"
end
end
class Polygon < Shape
end
class Square < Polygon
def describe
super
puts "with four equal sides"
end
end
Square.new.describe
Lookup climbs from Square to Polygon to Shape until it finds a match. super moves one step along that chain.
When Inheritance Is Appropriate
Use inheritance when the child truly is a specialized version of the parent. A Dog is an Animal; a SavingsAccount is an Account. The relationship should read naturally with the phrase "is a."
Prefer composition when
- You only need to reuse a small piece of behavior
- The relationship is "has a" rather than "is a"
- Deep hierarchies would become hard to follow
Modules and mixins, covered next, often provide reuse without tight coupling.
Common Mistakes
- Forgetting super and losing parent initialization
- Creating deep hierarchies that are difficult to navigate
- Overriding methods without understanding lookup order
- Using inheritance purely for code sharing when a module would be cleaner
Favor shallow hierarchies: one or two levels keep mental models manageable.
Method Resolution Order
When you call a method on an object, Ruby searches for it starting at the object actual class, then moves up through included modules, then up the superclass chain. This order means a method defined in a more specific class always wins over one defined in a parent class. Modules mixed into the class sit between the class itself and its superclass in the lookup path.
Super and Method Customization
The super keyword calls the same method one level up the inheritance chain, letting you extend parent behavior without duplicating it. You can call super with arguments to pass customized values or with parentheses empty to forward the original ones. This pattern is central to building layered architectures where each subclass adds a focused responsibility on top of shared base functionality.
Modules in the Lookup Chain
When a class includes a module, Ruby inserts that module into the method lookup path between the class and its superclass. This means module methods override inherited superclass methods but are themselves overridden by methods defined directly in the class, giving you precise control over behavior layering.
Key Takeaways
💡
- Subclasses inherit methods from their superclass using the less-than symbol
- Overridden methods take precedence during lookup
- super calls the parent version of the current method
- ancestors reveals the full method lookup chain
- Prefer composition or mixins when an is-a relationship does not exist
Practice Questions
- Create a Vehicle superclass and a Car subclass with an extra method.
- What does super do inside an overridden initialize?
- List the general order of Ruby's method lookup.
- How can you inspect an object's ancestors?
- Give an example where composition is better than inheritance.
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- Forgetting constraints — Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions