Ruby - Extending Objects using module

Introduction

You can add the methods of a module to a specific object rather than to an entire class using the extend method:

module A
    def method_a
        puts( 'hello from a' )
    end
end

class MyClass
    def mymethod
        puts( 'hello from mymethod of class MyClass' )
    end
end

ob = MyClass.new
ob.mymethod       #=> hello from mymethod of class MyClass
ob.extend(A)

The object ob is extended with the module A, it can access that module's instance method, method_a:

ob.method_a      #=> hello from a

You can extend an object with several modules all at once.

Here, the modules B and C extend the object, ob:

module B
   def method_b
       puts( 'hello from b' )
   end
end

module C
   def mymethod
       puts( 'hello from mymethod of module C' )
   end
end

ob.extend(B, C)
ob.method_b       #=> hello from b
ob.mymethod       #=> hello from mymethod of module C

Related Topic