Modules
Modules are a way to encapsulate methods, classes, and constants into a single, separate namespace. Modules provide two main benefits: they act as containers for reusable code, and they enable a form of multiple inheritance through a mechanism called "mixins."
module Greetings
def say_hello
puts "Hello!"
end
def say_goodbye
puts "Goodbye!"
end
end
class Person
include Greetings # Include the Greetings module to use its methods
attr_accessor :name
def initialize(name)
@name = name
end
end
# Create an instance of the Person class
person = Person.new("John")
# Use methods from the Greetings module
person.say_hello # => Hello!
person.say_goodbye # => Goodbye!
The Person
class includes the Greetings module as a minxin
using the include
keyword.
Modules are often used to share functionality between classes without using traditional inheritance. They allow you to group related methods together and include them in multiple classes.
Code Challenge
Create a module called
ShapeMixin
that provides methods for calculating the area and perimeter of different shapes. Include this module in two different classesRectangle
andCircle
to enforce the required methods on them.