Fourth article in the Prepare for a Ruby job interview series. In this article, we will study Include
and Extend
and see the differences between those two.
There is a big difference between include
and extend
in Ruby. Let me show you some code to explain it :
module Printable
def self.class_method_x
p 'class_method_x'
end
def instance_method_y
p 'instance_method_y'
end
end
class ExtendDocument
extend Printable
end
class IncludeDocument
include Printable
end
First round, on the Printable module :
Printable.class_method_x
# => "class_method_x"
Printable.instance_method_y
# => NoMethodError: undefined method `instance_method_y' for Printable:Module
Second round, on ExtendDocument :
ExtendDocument.class_method_x
# => NoMethodError: undefined method `class_method_x' for ExtendDocument:Class
ExtendDocument.instance_method_y
# => "instance_method_y"
And on an instance of ExtendDocument :
ExtendDocument.new.class_method_x
# => NoMethodError: undefined method `class_method_x' for #<ExtendDocument:0x007fe9e308ac08>
ExtendDocument.new.instance_method_y
# => NoMethodError: undefined method `instance_method_y' for #<ExtendDocument:0x007fe9e3080370>
Oops, nothing is working !
Last round, on IncludeDocument :
IncludeDocument.class_method_x
# => NoMethodError: undefined method `class_method_x' for IncludeDocument:Class
IncludeDocument.instance_method_y
# => NoMethodError: undefined method `instance_method_y' for IncludeDocument:Class
And on an instance of IncludeDocument :
IncludeDocument.new.class_method_x
# => NoMethodError: undefined method `class_method_x' for #<IncludeDocument:0x007fe9e3056480>
IncludeDocument.new.instance_method_y
# => "instance_method_y"
As you’ve probably noticed, Extend a module inside a class will add the instance methods defined in the module to the extended class.
The Include will add the instance methods defined in the module to the instances of the class including the module.
If you’re still not sure about the difference, take a closer look at the examples.
Continue to the fifth part about Ruby loops.