In this article, we will study Include
and Extend
and see the differences between those two. Include is for adding methods to an instance of a class and extend is for adding methods to any type of object(Class or an instance of Class). Let’s take a look at a small example:
1 | module Foo |
on IncludeModule:
1 | IncludeModule.bar # => undefined method `bar' for IncludeModule:Class (NoMethodError) |
As you can see, include a module inside a class will add the instance methods defined in the module to the instances of the class including the module.
on ExtendModule:
1 | ExtendModule.bar # => 'foobar' |
Extend a module inside a class will add the instance methods defined in the module to the extended class.
on an instance of Plain Class:
1 | plain = Plain.new |
Extend a module on an object will add the instance methods defined in the module to the object, and the module will not available in other objects.