Here are the differences between Include, Load,Require and Extend methods in Ruby :
--> Include:
When you Include a module into your class as shown below, it’s as if you took the code defined within the module and inserted it within the class, where you ‘include’ it. It allows the ‘mixin’ behavior. It’s used to DRY up your code to avoid duplication, for instance, if there were multiple classes that would need the same code within the module.
The following assumes that the module Log and class TestClass are defined in the same .rb file. If they were in separate files, then ‘load’ or ‘require’ must be used to let the class know about the module you’ve defined.
module Log
def class_type
"This class is of type: #{self.class}"
end
end
class TestClass
include Log
# ...
end
tc = TestClass.new.class_type
The above will print “This class is of type: TestClass”
--> Include:
When you Include a module into your class as shown below, it’s as if you took the code defined within the module and inserted it within the class, where you ‘include’ it. It allows the ‘mixin’ behavior. It’s used to DRY up your code to avoid duplication, for instance, if there were multiple classes that would need the same code within the module.
The following assumes that the module Log and class TestClass are defined in the same .rb file. If they were in separate files, then ‘load’ or ‘require’ must be used to let the class know about the module you’ve defined.
module Log
def class_type
"This class is of type: #{self.class}"
end
end
class TestClass
include Log
# ...
end
tc = TestClass.new.class_type
The above will print “This class is of type: TestClass”