Friday, June 25, 2010

Include Vs Extend in Ruby

Include vs Extend

Include

Classes and modules can include modules and reuse the methods defined in the module. The method in the module is available as an instance method. The constants, methods and module variables are available once the module is mixed in.

Extend

You can extend an instance of any class with module. The method in the module is available as an instance method.

The difference is extend is only applicable for that particular instance which was extended. Where as the include is applicable to any instance of the class.

Screen cast IncludeExtend.mov

Addition to IncludeExtendRuby.mov

module Talkable
def talk
p "hi"
end
end

class Foo

end

Foo.extend Talkable

Foo.talk


If extend is used on the class instead of the object, the method becomes available as class method. The extend can be used inside the class or outside the class. Refer the screencast to see how it works.