Modules and Classes aren't as similar as they appear in Ruby

Should you use a Class or a Module?

Modules and Classes have many distinct features in Ruby

At first glance, it may seem as though Modules and Classes perform the same function in a Ruby program. In reality, there are many very important distinctions between the two.

The first main difference you need to understand is that Classes allow instantiation of an object. Modules cannot do this. Thus, Classes give us the ability to create objects, whereas Modules perform more as a library of methods and Classes.

As such, Modules can be included in classes or modules. A Class that is inside a module can be included via inclusion of the module, but cannot be included directly.

Both Classes and Modules can contain methods. So, where would we use a Class instead of a Module? The main usage of a Class is to create an object. When we have an object that needs to be modeled, we are going to use a class. If we need to have instances of that object, we clearly need a class. If we simply need a method or methods that will be called in multiple areas of our code or if we need to namespace our variables, we are going to use a Module.

Namespacing, and/or organization of code is one of the main uses for Modules. If you are creating code that may be used by many developers in different applications, namespacing becomes very important to ensure that none of your variables end up conflicting with variables in other parts of an applications code.

The other major difference between the two is inheritance. As is well known, Classes in Ruby have the ability to inherit behavior and pass behavior on to children. Modules, on the other hand do not have the ability to inherit behavior.

In summary, use Modules to namespace and organize libraries of code which may include Classes. Use Classes any time that you need to create an object. Understanding the differences between the two is essential to write good code in Ruby.

 
 

Let's do something EPIC!