When to write modules in Ruby!?

To be short and concise, As soon as you have identified a behavior that is or may be shared between different objects, at that time it is a good idea to push that behavior in its own module.

So lets fabricate a use case;

You are given the task to write a little program for a zoo. They need to register the type of food and the time for which the different animals are fed. The zoo has a wide variety of animals, like big cats, fishes, reptiles etc.

So as a good programmer, we do know that all these animals ”eat” (Common behavior). So eating is a good candidate to be separated in a module. The different animals may implemented differently depending on the type, race etc.

So if we define an module and call it EatingBehavior that would look like this;

We can later define a Lion and a Fish class that may look like these;

The both objects are now ”eaters” and if we would define more animals, we should just repeat the same ”including” process….

To test the implementation;