Use and difference of require, include, load and extend

Source: Internet
Author: User
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"

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.