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