Differences between require, load, include, and extend IN Ruby: rubyrequire

Source: Internet
Author: User

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

Related Article

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.