Ruby modules are powerful tools for organizing and sharing code. They serve as containers for methods, constants, and classes, promoting code reusability and maintainability.
To create a module in Ruby, use the module
keyword followed by the module name in CamelCase:
module MyModule
# Module contents go here
end
You can define methods within a module just like you would in a class:
module Greeting
def say_hello(name)
puts "Hello, #{name}!"
end
end
Modules can also contain constants, which are useful for storing configuration values or other fixed data:
module MathConstants
PI = 3.14159
E = 2.71828
end
Modules are excellent for Ruby Namespaces, helping to avoid naming conflicts:
module Animals
class Dog
def speak
puts "Woof!"
end
end
end
Animals::Dog.new.speak # Output: Woof!
To use module methods as instance methods in a class, include the module:
class Person
include Greeting
end
person = Person.new
person.say_hello("Alice") # Output: Hello, Alice!
For more details on including modules, see Ruby Module Inclusion.
Modules in Ruby are frequently used for:
Ruby module creation is a fundamental concept for organizing and structuring code. By mastering module creation, you'll be able to write more maintainable and reusable Ruby code. For more advanced topics, explore Ruby Mixins and Ruby Metaprogramming.