這篇文章主要介紹了Ruby中require、load、include、extend的區別介紹,require、load用於檔案,如.rb等等結尾的檔案,include、load則用於包含一個檔案中的模組,需要的朋友可以參考下
require,load用於檔案,如.rb等等結尾的檔案。include,load則用於包含一個檔案中的模組。
require 一般情況下用於載入庫檔案,而load則用於載入設定檔。
1、require:載入一個庫,並且只載入一次,如果多次載入會返回false。只有當要載入的庫位於一個分離的檔案中時才有必要使用require。使用時不需要加副檔名,一般放在檔案的最前面:
代碼如下:
require ‘test_library'
2、load:
load用來多次載入一個庫,必須指定副檔名:
代碼如下:
load ‘test_library.rb'
3、extend:在定義類時使用,把module的執行個體方法作為當前類的類方法.
代碼如下:
module Test
def class_type
"This class is of type:#{self.class}"
end
end
class TestClass
extend Test
end
puts TestClass.class_type #=> This class is of type:Class
4、include:在定義類時使用,把module的執行個體方法作為當前類的執行個體方法. 把module的變數作為當前類的類變數.
include並不會把module的執行個體方法拷貝到類中,只是做了引用,包含module的不同類都指向了同一個對象。如果你改變了module的定義,即使你的程式還在運行,所有包含module的類都會改變行為。
代碼如下:
module Test
@a = 1
def class_type
"This class is of type:#{self.class}"
end
end
class TestClass
include Test
end
# puts TestClass.class_type #=> undefined method `class_type' for TestClass:Class (NoMethodError)
puts TestClass.new.class_type #=> This class is of type:TestClass