On Nov 15, 10:38 am, "jack.tang" <him... / gmail.com> wrote:
> I am new to ruby, and one question here: what object should I wrap as
> Module and what should I wrap as Class, any rules to fellow?

Hi Jack,

Modules in a certain sense are more than one thing, and that can make
them hard to figure out.

In one sense, a Module is a stripped down Class.  And as Ilan pointed
out, Class is itself a subclass of Module, so Class can take Module's
basic functionality and build upon it.  You can instantiate a Class
but not a Module.

So that's one way of understanding Modules.  But the more practical
way of understanding Modules is in how they're used.  And they're used
in two very distinct ways.

The first way you use Modules is to collect a set of instance
methods.  Now, what use could this have if you can't instantiate a
Module, you may ask.  Well a Class can "include" a Module and that
drops those instance methods in the class.  This is called a "mix-in"
module, and you can define the methods in one place and mix them into
a number of Classes.  For example, the Comparable module is a mix-in
module.  If you define the <=> operator in your class and then mix in
Comparable, it will create five more operators (<, <=, >, >=, and ==)
and one method (between?) all based on the <=> operator you defined.
So now you can easily use the comparison operators for your Invoice
class or your Employee class.

But then there is a second use of Modules, and that is to define a
name-space, a space where you can name things -- Classes, methods, and
other Modules -- without worrying that the names might conflict with
other names defined elsewhere in your software.  If you're familiar
with Java's packages, then this use of Modules is similar to that.

When you define a method in a Module that you're using as a name-
space, then you define it a class method.  You can then call it by
prepending the Module's name and two colons before the method name, as
in:

    MyModule::my_method(1, 'a', 2.2)

And you can also Classes and other Modules within the Module.  If
you've used Rails you've probably seen this taken to a high degree,
allowing it to subdivide all its functionality into nice units.  For
example, there's a module three deep -- ActiveRecord::Acts::List .

I hope that's helpful!

Eric

====

Interested in hands-on, on-site Ruby training?  See http://LearnRuby.com
for information about a well-reviewed class.