[Ruby basics] I tried to learn modules (Chapter 1)
1. Module overview
Modules are used for a variety of purposes.
In particular
- Add an instance method to your class without inheritance. Or overwrite (mixin)
- Add a common singular method (class method) for multiple classes (mixin)
- Define a functional method
- Treat like a singleton object and hold settings etc.
It is difficult to understand from the above definition alone, so let's learn while actually creating a module.
1. 2. Module definition
** How to make a module **
module module name
Module definition (methods, constants, etc.)
end
(Example)
module.rb
#Define a Greeter module with a hello method
module Greeter
def hello
'hello'
end
end
** At first glance it looks like a class definition, but modules are very different from classes **
- Cannot create an instance from a module
- Cannot inherit other modules or classes
References
"Introduction to Ruby for Professionals"