Ruby module inclusion is a fundamental concept that allows developers to add functionality to classes without using inheritance. It's a cornerstone of Ruby's approach to code reuse and organization.
Module inclusion is the process of incorporating a module's methods into a class. This technique enables you to share behavior across multiple classes without creating complex inheritance hierarchies.
To include a module in a class, use the include
keyword followed by the module name. Here's a simple example:
module Greetable
def greet
puts "Hello, #{name}!"
end
end
class Person
include Greetable
attr_reader :name
def initialize(name)
@name = name
end
end
person = Person.new("Alice")
person.greet # Output: Hello, Alice!
In this example, the Person
class includes the Greetable
module, gaining access to its greet
method.
Ruby allows you to include multiple modules in a single class. This feature provides even greater flexibility in composing class behavior.
module Swimmable
def swim
puts "#{name} is swimming."
end
end
module Runnable
def run
puts "#{name} is running."
end
end
class Athlete
include Swimmable
include Runnable
attr_reader :name
def initialize(name)
@name = name
end
end
athlete = Athlete.new("Bob")
athlete.swim # Output: Bob is swimming.
athlete.run # Output: Bob is running.
While both Ruby inheritance and module inclusion allow code reuse, they serve different purposes:
Module Inclusion | Inheritance |
---|---|
Adds behavior to a class | Creates an "is-a" relationship |
Can include multiple modules | Single inheritance only |
Ideal for sharing behavior across unrelated classes | Best for creating hierarchies of related classes |
Module inclusion is a powerful tool in Ruby's object-oriented programming toolkit. By mastering this concept, you'll be able to write more modular, maintainable, and flexible code.