Splitting code into several files allows us to reuse code and conform to the DRY principle. To do this we may have to use require, include or load statements in our file.
The differences between them are subtle and confusing, so I will make an attempt to explain:
load
The load method reads and parses another files into your code every time a script is executed.
For example, if we have some module in one file..
sum_module.rb
1 | module SumModule |
sum_class.rb
1 | load 'sum_module.rb' |
then we can use the load sum_module.rb
just before the class definition in sum_class.rb
file to get the access to yolo function contained in our module.
require
This method reads the file from the file system, parses it, saves to memory and runs it in place.
Simply put, even if you were to change the required file when the script is running, those changes will not be applied; Ruby will use the file in memory, not the original file from the file system.
Also, there is no need to specify the .rb
extension of the library file name.
It is similar to load but will load the file only ONCE!
It keeps track of whether a library was already loaded or not.
Q: Why would we ever need to use load instead of require?
A: Use load when your modules changes frequently and you want to pick up these changes in classes that load these modules.
include
When you include a module into your class it is as if you took code defined within a module and inserted it within the class, where you ‘include’ it.
The Ruby include is nothing like the C include. The Ruby include statement “mixes in” a module into a class. It’s a limited form of multiple inheritance.
On the other hand include in C language replaces the #include line, by the content of the file. Included files don’t have to be ‘header’ and #include don’t have to be at the beginning of file but can be anywhere, like in class or even a method definition.
Hope this helped you!