Modules & Mixins in Ruby
Organize code with modules, include shared behavior via mixins, and use extend and prepend in Ruby.
What is a Module?
A Ruby module serves two purposes: (1) namespace — grouping related constants and methods under a name, and (2) mixin — sharing behavior with classes without inheritance.
1. Module as Namespace
Avoid naming collisions.
2. Module Constants
Define shared constants inside a module.
3. Module Methods
Call methods directly on the module.
Mixins with include
include adds module methods as instance methods of the class. This is the core mechanism for mixins in Ruby — it enables multiple inheritance of behavior.
1. Basic include
Mix module methods into a class.
2. Built-in Mixin: Comparable
Add comparison operators automatically.
3. Built-in Mixin: Enumerable
Get map, select, sort, etc. for free.
Mixins with extend
extend adds module methods as class methods (not instance methods). Use it when you want to add behavior to the class itself.
1. extend — Class-Level Methods
Add methods to the class, not instances.
2. include vs extend
Side-by-side comparison.
prepend — Override Methods
prepend inserts the module before the class in the method lookup chain. This lets the module intercept and wrap class methods — useful for logging, caching, or decorators.
1. prepend Example
Intercept method calls.
Method Lookup Order (MRO)
Ruby searches for a method in this order: prepended modules → the class itself → included modules → superclass (and its modules) → BasicObject.
1. ancestors — See the Lookup Chain
Inspect the method resolution order.
2. Multiple Mixins
Include multiple modules in one class.