In Ruby, modules are a way to group together methods, classes, and constants into logical units. Modules are similar to classes in that they allow you to define methods and constants, but unlike classes, you cannot create instances of a module.
![]() |
Here's an example of how to define a module in Ruby:
module MyModule def say_hello puts "Hello from MyModule!" end end
In this example, we define a module called MyModule that has a single method called say_hello.
We can then include this module in a class using the include keyword, like this:
class MyClass include MyModule end
This means that the methods and constants defined in the MyModule module are now available to instances of the MyClass class. We can then call the say_hello method on an instance of MyClass like this:
my_object = MyClass.new my_object.say_hello
This will output the message "Hello from MyModule!".
Modules can also be used for namespacing. For example, we could define a module called MyNamespace and then define classes and methods within that module like this:
module MyNamespace class MyClass def my_method puts "Hello from MyNamespace::MyClass!" end end end
We can then create an instance of MyNamespace::MyClass and call its my_method method like this:
my_object = MyNamespace::MyClass.new my_object.my_method
This will output the message "Hello from MyNamespace::MyClass!".
In addition to including modules in classes, we can also extend individual objects with modules using the extend keyword. This allows us to add functionality to an object on a per-object basis, rather than at the class level. For example:
module MyExtension def my_method puts "Hello from MyExtension!" end end my_object = Object.new my_object.extend(MyExtension) my_object.my_method
This will output the message "Hello from MyExtension!".
0 Comments