Take the 2-minute tour ×

Can you tell me where we should use modules and where classes? I mean what is the usability and applicability principle for modules in Ruby?

share|improve this question
you should check out this Ruby Rogues podcast for some answers - When to use Modules –  pferdefleisch Jul 18 '12 at 14:32

4 Answers 4

Modules are collections of methods and constants. They cannot generate instances. Classes may generate instances (objects), and have per-instance state (instance variables). Modules may be mixed in to classes and other modules. The mixed-in module's constants and methods blend into that class's own, augmenting the class's functionality. Classes, however, cannot be mixed in to anything. A class may inherit from another class, but not from a module. A module may not inherit from anything. --Ruby FAQ

Classes are reliable abstractions with only what matters and Modules are containers that can give me informations or services and furthermore can be a place to keep singularity. For example, we could classify shy people and timidity be a singularity of this classification. ShyPeople may be a class and Timidity a module included in ShyPeople class.

'What matters?','Is it a module's method or a class' method?' or 'will it be a class or a module?' are questions that only experience and RL's analogies can help you. For more details I recommend to you reading and coding :)

share|improve this answer

My simple rule of thumb is if I need to keep the inner state of an object, for example creating instance variables, I will use a class.
I use modules for everything else. This includes namespacing, mixins and utility objects.

some basic Namespacing and Mixin info

share|improve this answer

Essentially, a Ruby module is like a class, but without the factory of objects part. Usually Ruby developers use modules to store groups of methods that have to be used by more than one class. This is, among other things, a great way to avoid using subclasses, that are very anti-rubyist pattern.

Anyway, that's almost a philosophical question that one can't answer properly in a short way. Maybe you should try to read a book about the Ruby basics (for example, Eloquent Ruby).

share|improve this answer

Classes ARE modules. The difference is that a class can be instantiated.

The usage of both is really dependent of how your class/module will be used, what it represents, ...

There are no ultimate answers to this question. In any case (imho), that is something you learn by reading and writing code, learning about idioms, design patterns, ...

share|improve this answer

Your Answer


