Ruby的include和extend
include主要用来将一个模块插入(mix)到一个类或者其它模块。extend 用来在一个对象(object,或者说是instance)中引入一个模块,这个类从而也具备了这个模块的方法。
通常引用模块有以下3种情况:
1.在类定义中引入模块,使模块中的方法成为类的实例方法
这种情况是最常见的
直接 include <module name>即可
2.在类定义中引入模块,使模块中的方法成为类的类方法
这种情况也是比较常见的
直接 extend <module name>即可
3.在类定义中引入模块,既希望引入实例方法,也希望引入类方法
这个时候需要使用 include,
但是在模块中对类方法的定义有不同,定义出现在 方法
def self.included(c) ... end 中
完整的示例如下:
module MaMA_VALUE = 1def ma_1 puts "it is ma_1"endendmodule MbMB_VALUE = 1def self.included(c) def c.mb_2 puts "it is mb_2" endenddef mb_1 puts "it is mb_1"endendclass Cainclude Ma endclass Cbextend Mainclude Mbendc1 = Ca.newc1.ma_1c2 = Cb.newc2.mb_1Cb.ma_1Cb.mb_2puts Ma::MA_VALUEputs Ca::MA_VALUEputs Mb::MB_VALUEputs Cb::MB_VALUE
页:
[1]