Ruby Modules
Organizing and sharing code across classes
📦 What are Ruby Modules?
Modules are containers for methods, constants, and classes. They help organize code and provide namespaces. Unlike classes, you cannot create instances of modules.
# Define a module
module Greetings
def say_hello
puts "Hello!"
end
end
class Person
include Greetings
end
person = Person.new
person.say_hello
Output:
Hello!
Key Module Concepts
Namespace
Group related code together
module Math
PI = 3.14
end
Include
Add module methods to class
include MyModule
Extend
Add module as class methods
extend MyModule
Constants
Store unchanging values
MAX_SIZE = 100
🔹 Creating Modules
Modules group related methods and constants together. They provide a way to organize code and prevent naming conflicts by creating separate namespaces:
module MathOperations
PI = 3.14159
def self.circle_area(radius)
PI * radius * radius
end
def self.square_area(side)
side * side
end
end
puts MathOperations::PI
puts MathOperations.circle_area(5)
puts MathOperations.square_area(4)
Output:
3.14159
78.53975
16
🔹 Including Modules
Use include to add module methods as instance methods in a class. This allows objects of the class to call the module's methods:
module Swimmable
def swim
puts "#{self.class} is swimming!"
end
end
module Flyable
def fly
puts "#{self.class} is flying!"
end
end
class Duck
include Swimmable
include Flyable
end
class Fish
include Swimmable
end
duck = Duck.new
duck.swim
duck.fly
fish = Fish.new
fish.swim
Output:
Duck is swimming!
Duck is flying!
Fish is swimming!
🔹 Extending Modules
Use extend to add module methods as class methods. This makes the methods available on the class itself, not on instances:
module Utilities
def format_name(name)
name.upcase
end
def format_date(date)
"Date: #{date}"
end
end
class Report
extend Utilities
end
puts Report.format_name("john doe")
puts Report.format_date("2025-01-07")
Output:
JOHN DOE
Date: 2025-01-07
🔹 Module Namespaces
Modules create namespaces to avoid naming conflicts. You can nest classes inside modules and access them using the :: operator:
module Company
class Employee
def initialize(name)
@name = name
end
def work
puts "#{@name} is working at Company"
end
end
end
module School
class Employee
def initialize(name)
@name = name
end
def work
puts "#{@name} is teaching at School"
end
end
end
emp1 = Company::Employee.new("Alice")
emp2 = School::Employee.new("Bob")
emp1.work
emp2.work
Output:
Alice is working at Company
Bob is teaching at School
🔹 Module Constants
Modules can store constants that are accessible throughout your program. Constants are written in uppercase and accessed using the :: operator:
module Config
APP_NAME = "MyApp"
VERSION = "1.0.0"
MAX_USERS = 1000
def self.info
"#{APP_NAME} v#{VERSION}"
end
end
puts Config::APP_NAME
puts Config::VERSION
puts Config::MAX_USERS
puts Config.info
Output:
MyApp
1.0.0
1000
MyApp v1.0.0