Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Difference between include & extend in Ruby Classes

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 388
    Comment on it

    Ruby provides us the facility of Modules. Modules is to ruby as package is to java and namespace is to c#.

    We use a module to keep similar kind of classes together, and promote code Re-usability, i.e If a set of code is to be used in multiple classes, we can keep them inside a module & then this module can be used in which-ever class we want. Thus this would remove code-duplication & will facilitate user for code-reuse.

    We can define a module in the same file in which a class would be using it, or it can be defined in a seperate file & then it can be loaded in the file in which a class wants to use the code written in that module.

    We can include a module in a class using include as follows :

    module ModuleExample
        def testMethod
            puts "This was printed from testMethod which belongs to module-ModuleClass"
        end
    end
    
    class TestClass
        include ModuleExample 
    end
    
    obj = TestClass.new()
    obj.testMethod()
    

    (This was the case when both module & class were defined in the same file say example.rb)


    So we can see that when we include a module in a class using the include statement, the methods defined in the module are added as instance method to the class. Thus we have to call those methods using the instance of the class.

    In the above example, we created the instance using new keyword as :
    obj = TestClass.new()

    and then we called the instance method which was included from the module to the class
    obj.testMethod()


    extend adds the module's method to the class as class methods rather than adding it as instance methods. Ex :-

    module ModuleExample2
        def testModuleMethod
            puts "The method testModule is now of type: #{self.class}"
        end
    end
    
    class TestClassNew
        extend ModuleExample2
    end
    
    TestClassNew.testModuleMethod()
    

    Here the extend keyword added the module's method as class methods to the TestClassNew class, thus we had to call them using the name of the class rather than calling them using the object of the class.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: