Instance methods in modules

freenight picture freenight · Nov 24, 2009 · Viewed 14.9k times · Source

Consider the following code:

module ModName
  def aux
    puts 'aux'
  end
end

If we replace module with class, we can do the following:

ModName.new.aux

Modules cannot be instanced, though. Is there a way to call the aux method on the module?

Answer

Chuck picture Chuck · Nov 24, 2009

Think about what aux is. What object will respond to aux? It's an instance method, which means that instances of classes that include ModName will respond to it. The ModName module itself is not an instance of such a class. This would also not work if you had defined ModName as a class — you can't call an instance method without an instance.

Modules are very much like classes that can be mixed into other classes to add behavior. When a class mixes in a module, all of the module's instance methods become instance methods of the class. It's a way of implementing multiple inheritance.

They also serve as substitutes for namespaces, since each module defines a namespace. But that's somewhat unrelated. (Incidentally, classes also have their own namespaces, but making it a class implies that you'll create instances of it, so they're conceptually wrong for that purpose.)