This article introduces the difference between require, load, include, and extend in Ruby, require, load for files, such as. RB, and so on, include, load is used to include the module in a file, Need friends can refer to the following
Require,load for files, such as. RB, and so on, at the end of the file. Include,load is used to include a module in a file.
Require is typically used to load library files, while load is used to load configuration files.
1, Require: Load a library, and only load once, if multiple loads will return false. Require is only necessary when the library to be loaded is in a detached file. You do not need to add an extension to use, usually at the front of the file:
The code is as follows:
Require ' test_library '
2. Load:
Load is used to load a library multiple times, and you must specify an extension:
The code is as follows:
Load ' test_library.rb '
3. Extend: When defining a class, use the instance method of module as the class method of the current class.
The 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 instance method of module as an instance method of the current class. Take the variable of module as the class variable of the current class.
Include does not copy the instance method of module to the class, but simply references it, and the different classes that contain the module point to the same object. If you change the definition of module, even if your program is still running, all classes containing the module will change behavior.
The 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