(轉)Ruby的include和extend

來源:互聯網
上載者:User

標籤:

include主要用來將一個模組插入(mix)到一個類或者其它模組。
extend 用來在一個對象(object,或者說是instance)中引入一個模組,這個類從而也具備了這個模組的方法。
通常引用模組有以下3種情況:
1.在類定義中引入模組,使模組中的方法成為類的執行個體方法
這種情況是最常見的
直接 include <module name>即可

2.在類定義中引入模組,使模組中的方法成為類的類方法
這種情況也是比較常見的
直接 extend <module name>即可

3.在類定義中引入模組,既希望引入執行個體方法,也希望引入類方法
這個時候需要使用 include,
但是在模組中對類方法的定義有不同,定義出現在 方法
def self.included(c) ... end 中

完整的樣本如下:

 1 module Ma    2   MA_VALUE = 1   3   def ma_1    4     puts "it is ma_1"   5   end    6 end    7    8 module Mb    9   MB_VALUE = 1  10   def self.included(c)   11     def c.mb_2   12       puts "it is mb_2"  13     end   14   end   15   def mb_1   16     puts "it is mb_1"  17   end   18 end   19   20 class Ca   21   include Ma      22 end   23      24 class Cb   25   extend Ma   26   include Mb   27 end   28   29 c1 = Ca.new  30 c1.ma_1   31   32 c2 = Cb.new  33 c2.mb_1   34 Cb.ma_1   35 Cb.mb_2   36   37 puts Ma::MA_VALUE   38 puts Ca::MA_VALUE   39   40 puts Mb::MB_VALUE   41 puts Cb::MB_VALUE  

 

(轉)Ruby的include和extend

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.