Introduction to require, load, include, and extend in Ruby _ruby topics

Source: Internet
Author: User
Tags extend instance method

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:

Copy Code code as follows:

Require ' test_library '

2. Load:
Load is used to load a library multiple times, and you must specify an extension:
Copy Code code as follows:

Load ' test_library.rb '

3, Extend:Used when defining a class, use the instance method of module as the class method of the current class.
Copy Code code 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:Used 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.
Copy Code code 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.