Modules & Mixins
Ruby classes can only inherit from a single parent class. To achieve multiple inheritance, Ruby provides Modules and Mixins.
1 Mixins vs Namespaces (include vs extend)
Modules wrap reusable methods and constants. Unlike classes, modules cannot be instantiated. They have two primary use cases:
- Namespaces: Groups related classes to prevent naming collisions.
- Mixins: Injects module methods directly into a class using the **`include`** keyword (methods act as instance methods) or **`extend`** keyword (methods act as class methods), implementing clean multiple inheritance.
2 Mixins Code
Let's run a program defining modules and mixing their methods into classes:
Ruby — Modules and Mixins
▶ Run Code
module Flyable
def fly
"I am flying high!"
end
end
module Swimmable
def swim
"I am swimming fast!"
end
end
class Duck
# Mixin both modules to achieve multiple inheritance
include Flyable
include Swimmable
end
donald = Duck.new
puts donald.fly
puts donald.swim
3 Code Challenge
Challenge: Create a module called `Loggable` with a method `log(message)` that prints a timestamped message. Include the module in a class called `Database` and invoke the `log` method.