Learn Ruby


In Ruby a Class can have methods. Similarly a Module can also have methods.

module Info
  def name
    puts "Roger Smith"

However we can’t call new on a Module. A moduled needs to be mixed in to a class. In other words we need to put the module in a class and then we need to instantiate that class. Then that class will have the methods defined in module.

How is module useful

Let’s say that we have a method called calculate_tax. This method does the complicated job of calculating tax. We do not want this method to be in many classes. We want this method to be at only one place so that we can make change to it.

We can do that by putting this method in a module. Now any class that needs to calculate tax can include the module and can do the tax calculation.