Included Modules, or “Mixins”
An object can access the instance methods of a module by including that module using the include
method. If you were to include MyModule
in your program, everything inside that module would suddenly pop into existence within the current scope. So, the greet
method of MyModule
will now be accessible:
modules2.rb
include MyModule
Note that only instance methods are included. In the previous example, the greet
(instance) method has been included, but the MyModule.greet
(module) method has not. As it’s included, the greet
instance method can be used just as though it were a normal instance method within the current scope, whereas the module method, also named greet
, is accessed using dot notation:
puts( greet ) #=> I'm happy. ...
Get The Book of Ruby now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.