More Ruby Fundamentals: Inheritance, Mixins, & Modules
Master Ruby's Advanced Object-Oriented Programming Concepts
Ruby Fundamentals You'll Master
Inheritance
Learn how objects inherit properties and methods from parent classes. Understand superclass-subclass relationships and method overriding.
Mixins & Modules
Discover Ruby's flexible approach to sharing methods between classes without requiring the same parent class structure.
Object Introspection
Master the is_a? and respond_to? methods to check object class membership and method availability at runtime.
This tutorial uses Interactive Ruby (IRB) for hands-on practice. You'll create real classes and see immediate results as you explore advanced Ruby concepts.
Building Your First Inheritance Hierarchy
Create Parent Class
Define a Pet class with attr_accessor :name, initialize method, and a speak method that returns 'Feed me!'
Create Child Class
Use the < symbol to create a Dog class that inherits from Pet: class Dog < Pet
Override Methods
Redefine the speak method in Dog class to return 'Arf! Arf!' instead of the parent's 'Feed me!'
Use Super Method
Create Fish class and use super to extend parent method: super + ' (bubble)' returns 'Feed me! (bubble)'
Method Override vs Super
| Feature | Override | Super |
|---|---|---|
| Result | Replaces parent method completely | Extends parent method functionality |
| Code Example | def speak 'Arf! Arf!' end | def speak super + ' (bubble)' end |
| Output | Arf! Arf! | Feed me! (bubble) |
| Use Case | Complete behavior change | Behavior enhancement |
Don't Repeat Yourself
Mixins vs Traditional Inheritance
Real-World Mixin Example
License Module
Created once with register method that works for both pets and cars. Demonstrates code reusability across different object types.
Pet Class Integration
Extended Pet class using 'include License' statement. All Pet subclasses automatically gain registration capability.
Car Class Integration
Car class includes same License module despite being unrelated to Pet hierarchy. Shows mixin flexibility.
is_a? vs respond_to? Methods
| Feature | is_a? | respond_to? |
|---|---|---|
| Purpose | Checks class membership | Checks method availability |
| Works with inheritance | Yes - checks parent classes too | Yes - includes inherited methods |
| Example usage | fido.is_a? Pet | fluffy.respond_to? :meow |
| Return type | Boolean (true/false) | Boolean (true/false) |
Object Introspection Best Practices
Returns true for both immediate class and parent classes
Prevents NoMethodError exceptions in dynamic code
More idiomatic Ruby than passing strings
Ensures both correct type and method availability
While respond_to? accepts both symbols (:meow) and strings ('meow'), using symbols is more idiomatic in Ruby and slightly more efficient.
Key Takeaways