Ruby中的require、load以及include
2016-09-17 11:11
471 查看
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)
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)
相关文章推荐
- ruby中load,require以及include,extend的区别
- Ruby中的require、load以及include
- Ruby 中 require load extend include 区别
- Ruby Require VS Load VS Include VS Extend
- 区别Ruby的require,load,和include
- 区别Ruby的require,load,和include
- Ruby中require、load、include、extend的区别介绍
- 区别Ruby的require,load,和include
- Ruby中Require、Load、Include和Extend的区别
- 『转』区分Ruby的require,load,和include
- require load include ruby
- 区别Ruby的require,load,和include
- 区别Ruby的require,load,和include
- Ruby 里的 include,require,load的显著区别
- Ruby中require,load,和include的区别
- Ruby的module 以及 require 和 include
- [转]Ruby中require、load和include区别
- Ruby中的require , load , include 的区别
- 区别Ruby的require,load,和include
- Ruby中Require、Load、Include和Extend的区别