Go Ruby's include and extend

Source: Internet
Author: User

Include is primarily used to insert a module (mix) into a class or other module.
Extend is used to introduce a module to an object (object, or instance), and this class also has the method of this module.
There are 3 common scenarios in which the reference module is:
1. Introduce the module in the class definition so that the method in the module becomes an instance method of the class
This situation is the most common
Direct include <module name>

2. Introduce a module in the class definition so that the method in the module becomes the class method of the class
This situation is also more common.
Direct extend <module name> can be

3. Introduce a module into a class definition, both to introduce an instance method and to introduce a class method
This time you need to use include,
However, there are different definitions of class methods in the module, and the definitions appear in the method
def self.included (c) ... end

The complete example is as follows:

1 Module Ma2Ma_value = 13   defma_14Puts"It is ma_1"  5 End6 End7   8 Module Mb9Mb_value = 1Ten   defself.included (c) One     defc.mb_2 APuts"It is mb_2"   - End - End the   defmb_1 -Puts"It is mb_1"   - End - End +    - classCa + include Ma A End at       - classCb - Extend Ma - include Mb - End -    inC1 =ca.new - c1.ma_1 to    +C2 =cb.new - c2.mb_1 the cb.ma_1 * cb.mb_2 $   Panax Notoginseng puts Ma::ma_value - puts Ca::ma_value the    + puts Mb::mb_value APuts Cb::mb_value

Go Ruby's include and extend

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.