Modules

Learn about modules in Ruby and how they relate with classes.

It now makes sense to introduce another language feature in Ruby: modules.

Modules are somewhat similar to classes in Ruby. They hold methods just like classes do. However, modules can’t be instantiated. It’s not possible to create objects from a module. Modules, unlike classes, don’t have a new method.

What are modules useful for?

We can share methods between classes with modules. Modules can be included into classes, and this makes their methods available in the class, just as if we’d copied and pasted these methods over to the class definition.

This is useful if we have methods that we want to reuse in certain classes but also want to keep in a central place so that we don’t have to repeat them everywhere.

A toy example

Let’s have a look at this pretty contrived code:

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy