Difference between require, include and load in Ruby on Rails

Shawn Rebello
  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


module SumModule
  def yolo
    # ...
  end
end

sum_class.rb


load 'sum_module.rb'
class SumClass

  # ...
end

...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! 
Drop a comment if you have any questions.

Shawn Rebello / Author & Editor

Shawn Rebello is an engineering student who likes learning new languages, tools, libraries or frameworks. When he is not coding, he binge watches TV shows and spends time on Wikipedia and Reddit.

1 comments :

Leave a comment here!