Include
When you include
a module into your class, 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.
module Log
def class_type
"This class is of type: #{self.class}"
end
end
class TestClass
include Log
# ...
end
tc = TestClass.new.class_type # -> success
tc = TestClass.class_type # -> error
Require
The require method allows you to load a library and prevents it from
being loaded more than once. The require method will return ‘false’ if
you try to load the same library after the first time. The require
method only needs to be used if library you are loading is defined in
a separate file, which is usually the case.
So it keeps track of whether that library was already loaded or not. You also don’t need to specify the “.rb” extension of the library file name.
Here’s an example of how to use require. Place the require method at the very top of your “.rb” file:
Load
The load method is almost like the require method except it doesn’t
keep track of whether or not that library has been loaded. So it’s
possible to load a library multiple times and also when using the load
method you must specify the “.rb” extension of the library file name.
Extend
When using the extend method instead of include, you are adding the
module’s methods as class methods instead of as instance methods.
module Log
def class_type
"This class is of type: #{self.class}"
end
end
class TestClass
extend Log
# ...
end
tc = TestClass.class_type
require
andinclude
, and also relevant,Module#append_features
. – user456814