Ruby Modules

Gary Cordero Rosa
2 min readMar 28, 2021

One of the concepts that you find along the way to becoming a great Rubyist is the concept module. A module is a way to wrap methods, classes, constant in a unit, in a way similar to a Class with the difference that a module can’t be instantiated.

You are probably wondering “If they can be instantiated then what is the use of an module?”. Well, modules have two main uses.

  1. Namespacing
  2. Utilizing Ruby Mixin

Namespacing

Namespacing is in a way a kind of container for functions, classes, constants, modules, etc … The idea of this is to used this container as an unique identifier for everything contained in it, to avoid clashes. Imagine you are using to gems with the same two classes, how would the compiler know which of the classes diffinition you are referring to.

An example of two identical classes existing with the same name and same methods.

As you can see the first class definition was completely overlooked by the compiler and the latter definition overshadowed the former. Now let’s apply a namespace to solve this problem.

Ruby Mixin

In order to understand ruby mixin, we need some understanding of object-oriented programming concepts and principles. Ruby mixings allows to do several thing like implement multiple inheritance which ruby doesn't support directly.

As we can see that the class Dog inherits from the two modules and shows a behavior similar to multiple inheritance or so to say a mixin.

--

--