Ruby中的require、load以及include

版权声明:开源交流,可以不进行特殊介绍,但请尊重个人劳动成果,互相交流哦! https://blog.csdn.net/wanglizheng825034277/article/details/52561923

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)

猜你喜欢

转载自blog.csdn.net/wanglizheng825034277/article/details/52561923