Ruby's modules are very similar to classes except:
Modules may not have entities
Modules may not have subclasses
Modules are defined by Module...end.
As a matter of fact... The module's ' Module class ' Is the class ' class ' parent class. Do you understand? Let's keep watching.
There are two ways to use a module. The first is to place similar methods and entities in a relatively focused domain. The math module in the Ruby Standard pack plays this role:
Ruby> math.sqrt (2)
1.41421
ruby> Math::P i
3.14159
:: The operator tells the Ruby interpreter where to find the value of the constant (as you can imagine, other modules outside of math use Pi to represent something else). If we want to dispense with: direct calls to a module's methods and constants, we can use include:
Ruby> include Math
Object
ruby> sqrt (2)
1.41421
ruby> PI
3.14159
Another use of modules is Leelawadee and (mixin). Some OO languages, including C + +, allow multiple inheritance (multiple inheritance) to inherit from multiple parent classes. One example of multiple inheritance in the real world is the alarm clock: You can imagine that the alarm clock belongs to the Bell class, which belongs to the thing with the buzzer.
Ruby does not specifically implement real multiple inheritance, but Leelawadee and technology are a good alternative. Remember that the module cannot be materialized or subclasses, but if we include a method in the class definition,
Its methods are actually joined, or "Blended" into this class.
Blending can be seen as a way of looking for all the specific attributes we want to get. For example, if a class has each method, blending the enumerable module in the standard library naturally gives us sort and find two methods.
The use of the module allows us to get the basic function of multiple inheritance but can express the class relationship through a simple tree structure, while also considerably simplifying the implementation of the language (Java designers have made a similar choice).