In this article, we’re going to explore the following topics:
- Anonymous modules
Feel free to read the Part 1 if you’re not familiar with namespacing and mixin facility in Ruby
Ruby is a fully object oriented programming language.
As we’ve seen in the article about classes in Ruby, a class is in reality an instance of the
So, as you guess, a module is strongly correlated to
In the part I we’ve seen that in Ruby, the
module keyword allows you to define a new module
Let’s see how to define the exact same module in Ruby without using the
Module.new method returns an object of type
This object is what we commonly call a module in Ruby.
By default, an instance of
Module can be assimilated to the concept of anonymous module.
But, the fact of storing this instance in a constant — the
Greeting one for example — changes the state of this instance from anonymous to named module.
This means that this instance will internally keep track of this constant and refer to it every time is needed.
Note that we can access the name of a
Moduleinstance via the
As we’ve seen in the above section, when a fresh instance of
Module is assigned to anything but a constant, then the module remains anonymous
m variable contains an instance of
A call to
nil as the module is anonymous.
So we refer to that instance as an anonymous module.
What’s happens if we assign this anonymous module to a constant?
Here we can see that the
m module passes from an anonymous to a named module after assigning it to a constant.
We can now use the
m.yo method by calling
Also, note that a call to the
m.name method returns
"Mod" after that the
m variable is assigned to the
Module and Class
Class are not only friends syntactically.
They also share two secrets.
Let’s have a look to the
superclass of the
Class class to figure it out
Class directly inherits from
Class is a specialisation of
Now, let’s see what’s
Module is an instance of the
So, to recap:
Definition of a class in Ruby
A class is an instance of the
Classclass stored in a constant.
Classclass is a specialisation of the
Moduleclass whose instances can be instantiated.
Definition of a module in Ruby
A module is an instance of the
Moduleclass stored in a constant.
Moduleclass is an instance of the
Classclass stored in a constant and whose instances cannot be instantiated.
May I have your attention please 🎤🎤
Feel free to subscribe here: www.rubycademy.com
Thank you for taking the time to read this post :-)
Feel free to 👏 and share this article if it has been useful for you. 🚀
Here is a link to my last article:
Modules in Ruby: Part I