tags:

views:

737

answers:

3

I came from Java and now I am working more with ruby. One language feature I am not familiar with is the module. I am wondering what exactly is a module and when do you use one? Also why use a module over a class?

A: 

I'm not sure of the exact definition in relation to Ruby, but in Python, Modules are containers for classes, They provide the benefit of a namespace to organize classes and use them across multiple source files with a simple include statement.

Further reading:

Classes: http://www.rubycentral.com/pickaxe/classes.html

Modules: http://www.rubycentral.com/pickaxe/tut_modules.html

junkforce
+8  A: 

This site has a good explanation of how modules are different.

Basically, the module cannot be instantiated. When a class includes a module, a proxy superclass is generated that provides access to all the module methods as well as the class methods.

A module can be included by multiple classes. Modules cannot be inherited, but this "mixin" model provides a useful type of "multiple inheritrance". OO purists will disagree with that statement, but don't let purity get in the way of getting the job done.

hurcane
+2  A: 

The first answer is good and gives some structural answers, but another approach is to think about what you're doing. Modules are about providing methods that you can use across multiple classes - think about them as "libraries" (as you would see in a Rails app). Classes are about objects; modules are about functions.

For example, authentication and authorization systems are good examples of modules. Authentication systems work across multiple app-level classes (users are authenticated, sessions manage authentication, lots of other classes will act differently based on the auth state), so authentication systems act as shared APIs.

You might also use a module when you have shared methods across multiple apps (again, the library model is good here).

scottru