ruby簡單的基礎 6

來源:互聯網
上載者:User

標籤:ruby

模組

模組同類一樣,也有 class method 和 instance method。
module 沒有new不能產生執行個體對象
其中 class method 在模組中稱為模組方法,是可以直接調用的。

module Foo  def self.hello    puts ‘hello world!‘  end  def Foo.dear #module全域範圍內的self還是沒有變,就是Module;  puts ‘dear..‘  end  NUM = 100end




Foo.hello   #=>  ‘hello world!‘ 調用模組方法 模組名字.方法名字
Foo.dear #=>  ‘dear..‘ 調用模組方法 模組名字.方法名字
Foo::NUM#=> 100 引用一個常數,使用模組名和兩個冒號。


而對於模組裡面的 instance method 執行個體方法,這種方法不能直接調用,需要mixin到一個類中。
主要有兩種形式:
一種是include,方法會被添加到執行個體方法中。
一種是extend,方法會被添加到類方法中。

module Mdef self.m_funputs ‘m fun‘enddef instance_funputs ‘instance fun‘endNUM = 100endM.m_funM::m_funputs M::NUMputs ‘-----------------‘class Ainclude Mend#A.m_fun#A.instance_fun#A.new.m_funA.new.instance_funputs ‘-----------------‘class Bextend Mend#B.m_funB.instance_fun#B.new.m_fun#B.new.instance_fun


一些總結require, load,include都是Kernel模組中的方法,他們的區別如下:


require,load用於包含檔案,include則用於包含的模組。


require載入一次,load可載入多次。


require載入Ruby代碼檔案時可以不加尾碼名,load載入代碼檔案時必須加尾碼名。


require一般情況下用於載入庫檔案,而load用於載入設定檔。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.