CSC/ECE 517 Fall 2011/ch4 4c dm: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
Line 13: Line 13:
     ...........
     ...........
   end
   end
Consider for example ,a module called MyModule , which defines the happy and the sad times.
  module MyModule
  GOODMOOD = "happy"
  BADMOOD = “sad”
  def greet
  return  "I'm #{GOODMOOD}. How are you?"
  end
  end
The above represents a module MyModule with a constant GOODMOOD and an “instance method” greet.
In addition to instance methods a module may also have module methods. Just as class methods are prefixed with the name of the class, module methods are prefixed with the name of the module:
  def MyModule.greet
  return "I'm #{GOODMOOD}. How are you?"
  end
In spite of their similarities, there are two major features which classes possess but which modules do not: instances and inheritance. Classes can have instances (objects), superclasses (parents) and subclasses (children); modules can have none of these.
Inspite of inability of the modules to be initialized and inherited., They provide a namespace and prevent name clashes and they implement the mixin facility.
==Modules as Namespaces==

Revision as of 17:56, 19 October 2011

4c Chapter 6

Regular Expressions

Modules

Modules provide a structure to collect Ruby classes, methods, and constants into a single, separately named and defined unit. This is useful so that one can avoid clashes with existing classes, methods, and constants, and also so that you can add (mix in) the functionality of modules into your classes. The definition of a module is very similar to a class. Also, modules and classes are closely related. The Module class is the immediate ancestor of the Class class. Just like a class, a module can contain constants, methods and classes.

In Ruby programming language , a module is defined in the following way

 module <module name>
   statement1
   statement2
   ...........
 end

Consider for example ,a module called MyModule , which defines the happy and the sad times.

 module MyModule
  GOODMOOD = "happy" 
  BADMOOD = “sad”
  def greet 
  return  "I'm #{GOODMOOD}. How are you?"
  end
 end

The above represents a module MyModule with a constant GOODMOOD and an “instance method” greet. In addition to instance methods a module may also have module methods. Just as class methods are prefixed with the name of the class, module methods are prefixed with the name of the module:

 def MyModule.greet
  return "I'm #{GOODMOOD}. How are you?" 
 end

In spite of their similarities, there are two major features which classes possess but which modules do not: instances and inheritance. Classes can have instances (objects), superclasses (parents) and subclasses (children); modules can have none of these. Inspite of inability of the modules to be initialized and inherited., They provide a namespace and prevent name clashes and they implement the mixin facility.

Modules as Namespaces