標籤: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用於載入設定檔。