What if you could give your class many superpowers without messy inheritance battles?
Why modules solve multiple inheritance in Ruby - The Real Reasons
Imagine you want a class in Ruby to have features from two different classes at once, like a car that can both fly and float on water. Without modules, you'd try to inherit from both classes directly.
Ruby does not allow a class to inherit from more than one class. Trying to do so leads to confusion and errors. You would have to copy and paste code or write complex workarounds, which is slow and error-prone.
Modules let you group reusable methods and include them in any class. This way, a class can gain multiple behaviors by mixing in several modules, avoiding the problems of multiple inheritance.
class FlyingCar < Car, Boat # Not allowed in Ruby end
module Flyable def fly; end end module Floatable def float; end end class FlyingCar < Car include Flyable include Floatable end
Modules let you combine many behaviors cleanly, making your code flexible and easy to maintain.
Think of a smartphone app that needs to send notifications and also handle payments. Instead of one big class, you mix in Notification and Payment modules to add these features separately.
Ruby classes can only inherit from one class, limiting direct multiple inheritance.
Modules provide a way to share reusable code across classes without inheritance conflicts.
Including multiple modules lets classes gain many behaviors simply and safely.