Sunday, June 10, 2012

Ruby Modules

Ruby Modules are similar to classes in that they hold a collection of methods, constants, and other module and class definitions. Modules are defined much like classes are, but the module keyword is used in place of the class keyword. Unlike classes, you cannot create objects based on modules nor can you subclass them; instead, you specify that you want the functionality of a particular module to be added to the functionality of a class, or of a specific object. Modules stand alone; there is no "module hierarchy" of inheritance. Modules is a good place to collect all your constants in a central location.

Modules are a way of grouping together methods, classes, and constants. Modules give you two major benefits:
  1. Modules provide a namespace and prevent name clashes.
  2. Modules implement the mixin facility. 
Modules define a namespace, a sandbox in which your methods and constants can play without having to worry about being stepped on by other methods and constants.

Syntax:

module Identifier
   statement1
   statement2
   ...........
end
Module constants are named just like class constants, with an initial uppercase letter. The method definitions look similar, too: module methods are defined just like class methods.
As with class methods, you call a module method by preceding its name with the module.s name and a period, and you reference a constant using the module name and two colons.

Example:

#!/usr/bin/ruby

# Module defined in trig.rb file

module Trig
   PI = 3.141592654
   def Trig.sin(x)
   # ..
   end
   def Trig.cos(x)
   # ..
   end
end
We can define one more module with same function name but different functionality:
#!/usr/bin/ruby

# Module defined in moral.rb file

module Moral
   VERY_BAD = 0
   BAD = 1
   def Moral.sin(badness)
   # ...
   end
end
Like class methods, whenever you define a method in a module, you specify the module name followed by a dot and then the method name.



No comments:

Post a Comment