Monday, April 16, 2012

Module Example in Ruby Language

The below given example guide you , how to work with ruby module.

1) The ruby module are just like ruby class , which can contain the methods , fields etc..
2) Multiple modules can possible in a file , lets take an example :

create a file testModule.rb , create it any where does not matter. In side the file create the module viz.
here we have created two modules

1)Test
2)Test1

Test contains a simple method as show , So that we can call this method just by using the object of the used class of this module Test

Test1 contains the same method , but the declaration is bit different that is Test1.show . which behaves like a static method, and you have to call this method using the Module name i.e.

"Test1.show" -----------------------------------------------------------------------------------------------------------
File :  testModule.rb
------------------------------------------------------------------------------------------------------------

module Test
    def show
        print "From method Show"
    end
end

module Test1
     def Test1.show
         print " From Method Show from Module Test1"
     end
end

------------------------------------------------------------------------------------------------

Now create another ruby file for ruby class , let demo.rb
------------------------------------------------------------------------------------------------
require File.dirname("File path ")+"/ testModule"

class Demo
include Test
include Test1

   def  demoMethod
      print " from demoMethod"
       Test1.show
   end

end

test=Demo.new
test.demoMethod
test.show


Description : "require" is the keyword which is similar to include and import in c/c++ and java

The required keyword search for the file from $LOAD_PATH , if not not found , there would be a error as file not found, So in this case you can give the file path name followed by the file name.

Test1.demo is just similar as static method call using class name reference in java

If the module name is not used before the method name at the time of defining it, then that method can be called using the used call object. here in the above example it is Demo and test is the object of the Demo class.