Differences between require, load, include, and extend IN Ruby: rubyrequire
Require and load are used to end files, such as. rb. Include and load are used to include modules in a file.
Require is generally used to load library files, while load is used to load configuration files.
1. require:Load a database only once. If the database is loaded multiple times, false is returned. Require is required only when the library to be loaded is in a separate file. You do not need to add an extension when using it. It is usually placed at the beginning of the file:
Copy codeThe Code is as follows:
Require 'test _ library'
2. load:
To load a database multiple times, you must specify the extension:
Copy codeThe Code is as follows:
Load 'test _ library. rb'
3. extend:When defining a class, use the module instance method as the class method of the current class.
Copy codeThe Code is as follows:
Module Test
Def class_type
"This class is of type: # {self. class }"
End
End
Class TestClass
Extend Test
End
Puts TestClass. class_type # => This class is of type: Class
4. include:When defining a class, use the module instance method as the instance method of the current class, and use the module variable as the class variable of the current class.
The include statement does not copy the instance method of the module to the class, but only references it. Different classes containing the module point to the same object. If you change the module definition, even if your program is still running, all classes containing the module will change the behavior.
Copy codeThe Code is as follows:
Module Test
@ A = 1
Def class_type
"This class is of type: # {self. class }"
End
End
Class TestClass
Include Test
End
# Puts TestClass. class_type #=> undefined method 'class _ type' for TestClass: class (NoMethodError)
Puts TestClass. new. class_type # => This class is of type: TestClass