Require, load, and autoload are the methods defined in the kernel module. because both the class and the object class are mixed into the kernel module, you can call these methods whether self is an object or a class.
These three methods are used to load and execute other files, but they are slightly different. In this article, we will briefly introduce these three functions in terms of parameters, function execution, and return values.
1. Require (name)-> true or false or raise loaderror
Http://ruby-doc.org/core-2.1.2/Kernel.html#method-i-require
- The name can be an absolute or relative path. Ruby automatically adds the name extension (. RB,. So,. etc );
- When the function is executed, if the name is an absolute path, the file will be searched;
- Generally, name is the relative path. Ruby searches for the file in the $: directory. Therefore, you usually need $:. unshift to add a search path;
- After the file is found, the file is run and the absolute path of the file is added to the global variable $ "to ensure that the file is not loaded repeatedly;
- Returns true upon first loading. If loading has already returned false, A loaderror will be thrown if the file cannot be found..
2. Load (filename, wrap = false)-> true or raise loaderror
Http://ruby-doc.org/core-2.1.2/Kernel.html#method-i-load
- Filename can be an absolute or relative path. Ruby does not add an extension for filename;
- When the function is executed, if filename is an absolute path, the file will be searched.
- Normally, filename is a relative path. Ruby searches for the file in the $: directory. Therefore, you usually need $:. unshift to add a search path;
- When wrap is true, the loaded file is executed in an anonymous module to avoid contamination;
- Load loads and executes the file. If the file is successfully loaded, true is returned. If the file is not found, a loaderror is thrown.
3. autoload (module, filename)-> nil or raise loaderror
Http://ruby-doc.org/core-2.1.2/Kernel.html#method-i-autoload
- Associate filename with the module. When the module is used for the first time, use require to load the file;
- The execution process is the same as that of require;
- If nil is returned successfully, a loaderror will be thrown if the file cannot be found.
4. Summary
The three methods have the following in common:
- $: Is searched to find the target file. If not found, loaderror is thrown.
The three methods can be roughly divided as follows:
- Require avoids repeated loading without specifying the extension;
- Load will be loaded repeatedly, and the extension must be specified;
- Autoload will be loaded with require when needed to avoid repeated loading without specifying the extension.
Therefore, autoload is more like require.