Ruby中require、load、include、extend的区别介绍
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
如对本文有疑问,
点击进行留言回复!!
相关文章:
-
循序渐进掌握递归正则表达式
一般来说,递归的正则表达式用来匹配任意嵌套层次的结构或左右对称的结构。例如匹配: 递归正则在正则表达式里算是比较灵活的部分,换句话说就是可能会比较难...
[阅读全文]
-
scrapy 使用
启动方式: 写一个启动文件,与配置文件同级 from scrapy.cmdline import execute import sys,os sys...
[阅读全文]
-
-
-
-
经典例题
例题: 1.用户输入账号 2.用户输入密码 3.判断用户的账号是不是alex 4.如果账号是alex在继续判断密码是不是alexdsb 5.账号和密...
[阅读全文]
-
-
-
-
-
网友评论