1. 程式人生 > >Ruby中的require、load以及include

Ruby中的require、load以及include

require、load以及include關鍵字都是在kernel中定義的,用來包含外部檔案或模組到當期程式中,下面就他們的具體區別進行部分闡述:

1、require:

require多引入外部rb原始檔或者外部庫(可以省略檔案的字尾‘.rb’),require載入外部檔案只會載入一次(多次引入會忽略),而load會載入多次

2、load:

load多為載入資源配置檔案,因為load可以多次載入(每次都重新載入)(配置檔案如***.yml等檔案),與require相比,除了會載入多次外,載入時需要新增檔案的字尾

3、include:

include多為載入原始檔中的模組,實現mix_in;同時include在定義類使用時,可以將模組的方法變為類的例項方法,變數變為當前類的類變數@@xxx;而與之相對的

extend關鍵字會將模組中的方法變為類的類方法

例項演示:

require載入外部庫或原始檔:

require ‘test_library’(或require 'test_library.rb')

load載入資源配置檔案:

load 'language.yml'

include載入模組例項:

module Test
	@a = 1
	def class_type
		"This class is of type: #{self.class}"
	end
end


class TestInclude
	# include Test
	def self.test_a
		puts "test @@xxx"
	end
	extend Test
end

# puts TestInclude.class_type  #=> undefined method 'class_type' for TestInclude:Class(NoMethodError)
# puts TestInclude.new.class_type #=> This class is of type: TestInclude
puts TestInclude.class_type	#=> This class is fo type:Class
puts TestInclude.new.class_type	#=> undefined method 'class_type' for TestInclude(NoMethodError)