Modules and Namespaces in Ruby
Ruby modules can act in two apostasies. They can group classes, modules, constants and act as namespaces. Math module is a good example of such a namespace with such known constants as Math:PI. Modules are also used as package for follow-up usage inside classes.
It is interesting to note that Module is a superclass of Class which makes every class also a module. The main difference between Ruby modules and classes is in impossibility to declare objects from it. So, we will never be able to call new on the module.
Math.new //will produce “undefined method new” error message
Modules are ideal for creating functionality that can be included in other classes and often times used to overcome Ruby’s lack of support for multiple inheritance.
class MyClass < String
include MyModule
end
We can see from the example above, that MyClass is a subclass of String and has access to String methods as well as capable of using MyModule methods at the same time. In other word, Ruby allows to have only one superclass but multiple modules which makes it very flexible for developers.