以下是對:require、load、include、extend的區別:
1)、require方法是加載一個文件,只加載一次,如果多次加載會返回false,一般在使用require加載一個文件的時候不需要加擴展名。如要加載test.rb文件時,require ‘test’。
2)、load方法跟require方法類似,也是加載一個文件,但是也有不同,就是它可以多次加載,而且必須制定擴展名。如要加載文件test.rb文件時, load "test.rb"
3)、include方法是引入模塊,前提是你在映入了庫之後,你可以在你的庫文件中定義module,然後通過include引入,但是這裏必須注意,使用include引入的module中的方法和變量爲實例方法和實例變量,而不是類方法和類變量。更進一步說,即使你的類還在運行,這個時候你去改變了你引入的module的定義,你就會相應的改變引入該模塊的類的行爲。
test.rb :
module Include_test
def say
"This class is of type: #{self.class}"
end
end
class Test
require 'test'
include 'Include_test'
end
Test.say #會報未定義該方法
Test.new.say #This class is of type: Test
4)、extend方法類似於include方法,但是通過extend映入的方法和變量會成爲類方法和變量,對象實例是沒有辦法去調用的
test.rb :
module Include_test
def say
"This class is of type: #{self.class}"
end
end
class Test
require 'test'
extend 'Include_test'
end
Test.say #This class is of type: Test
Test.new.say #會報未定義該方法