These four methods are very useful and easy to mix.
1. Require (astring)-> true or false
Ruby tries to load a database named astring. If it succeeds, true is returned. Otherwise, false is returned. If the given value is not an absolute path, it will be searched in $. If the given name has. RB is loaded as the source file. If the extension is. so ,. O ,. DLL (based on different platforms), Ruby loads these files as extensions; otherwise, Ruby automatically tries to add them after the given file name. RB ,. so ,. DLL. The loaded library will be placed in the array $ ", and those already in $" will not be repeatedly loaded. For example:
Require "my-library.rb" Require "DB-driver" |
2. Load (afilename, wrap = false)-> true
Load and execute the afilename file. The file search method is the same as the above require. WRAP is an optional parameter. The default value is false. If it is set to true, the file runs in the anonymous module, including the caller's namespace. Local variables in any afilename are not available in the environment where they are loaded.
3. Include
Include is used to insert a module into a class or other modules. The method of this module is called in the form of a function in the class or module that introduces it (there is no aggreger ). This command runs the module. append_features method.
4. Extend
Extend is used to introduce a module into an object (object, or instance). This class also provides the method of this module.
Module mod Def hello2 "Hello from Mod. N" End End Class Klass Def hello "Hello from Klass. N" End End K = Klass. New K. Hello # "hello from Klass. N" K. hello2 # nomethoderror: Undefined method 'hello2 '... K. Extend (MOD) # <0x2e4c530> 0x2e4c530> K. Hello # "hello from Mod. N" |