A module is similar to a class, and it can also be said to be "a class that cannot be instantiated." Because class classes are subclasses of the module class, it might be better to say "class = module + instantiation capability."
What is the so-called module, what is it used for? There are two main types of functions: Mix-in and namespaces.
Mix-in are actually restricted multiple inheritance. Using the actual inheritance relationship, you can achieve some "embellishment" to some classes. In fact, Mix-in's argument comes from cookies or nuts on ice cream.
In the history of object-oriented design, the problems caused by multiple inheritance mechanisms have long been known. Therefore, many modern object-oriented design languages only support a single inheritance approach. That's the way Ruby is used.
However, multiple inheritance mechanism also has the charm that cannot be abandoned. So Ruby introduced many of the advantages of multiple inheritance by adopting a mix-in approach.
If a class inherits multiple classes at the same time, it is easy to have many problems with object-oriented design. As a result, Ruby adds the following restrictions:
1. Only one class can be inherited
2, can inherit a number of so-called "like class but not class" module
In addition, Ruby calls the "Add modules in class" action called include.
Another function of the module is to provide namespaces
In large-scale program development, the problem of naming conflicts often arises. For example, the reader needs to make a class in the program called Service, but the name of the service has been used in the library, which is the problem of naming conflicts.
In many modern programming languages, in order to avoid the problem of naming conflicts, the function of namespaces or packages is basically provided. Service classes that exist in different namespaces are treated as different objects, although the class names are the same.
In Ruby, modules are often used to provide such namespaces.
Class Service; End
Module Library
class Service;
The first service class is the namespace of the top level, and the following service class belongs to the library module.
This is essentially a constant named service (the class name is actually a constant pointing to the class object) defined in the top level and the library module respectively.
Therefore, it is used as a constant.
:: Service #Top level service
library::service #Library的Service