Buy @ Amazon

Require versus Load in Ruby

The big difference

  • While you load a file, you require a feature
  • Every time you load, you load a file into memory. On the other hand, every time you require you is if it has already been required to avoid repetition
  • require is more abstract an API than load. So typically for you're day to day use, you'd require not load.
  • Because you load a file, the load method takes the input argument having file extension. The file extension is excluded in the case of require method.


How require works?

require(filename) -> true or false

It's good to understand how require works under the hood to serve as the high level utility method that it is. 

When you require with a string argument, the file-name is resolved to an absolute path. If the filename does not resolve to an absolute path, it will be searched for in the directories listed in $LOAD_PATH ($:).

If the file is not to be found a LOADError is raised. Otherwise, this resolved file-path is added to the $LOADED_FEATURES array.

It is also good to know that require method returns a boolean true/false depending on weather it is loaded or not.

Side-note: require(..) has similar sibling method require_relative(..) that you can take a peek into.


How load works?

load(filename, wrap=false) -> true or false

Loads and executes the code in the file filename.

If the filename does not resolve to an absolute path, the file is searched for in the library directories listed in $LOAD_PATH ($:).

Setting wrap=true gives additional benefit in that the loaded ruby code is wrapped into an anonymous module before being executed so as to avoid any naming collisions or dirtying the program's global namespace.


Understanding Require and Load by example

Fork my repo ruby_lab and play your way with files in require_load directory to get better understanding.