原文:Ruby Require VS Load VS Include VS Extend
include
如下例当Include一个模块到某个类时, 相当于把模块中定义的方法插入到类中。Include一个模块实际上相当于将其mixin到某个类中。它遵循 DRY(Don’t repeat yourself)原则, 避免重复。例如,当有多个类需要引入模块中的同一段代码时。
下例假设Log模块和TestClass类被定义在同一个.rb文件中。如果它们位于不同文件,则要使用’load’或’require’方法来引入代码。
module Log
def class_type
"This class is of type: #{self.class}"
end
end
class TestClass
include Log
# ...
end
tc = TestClass.new.class_type
puts tc
打印结果:”This class is of type: TestClass”
load
除了不会记录库是否被加载过之外,load方法和require方法功能几乎一样。所以使用load方法可以对库进行多次加载,另外注意要指定库文件的.rb扩展名。
大多数时候可以使用require来代替load,除非是想每次对库进行重新载入。例如,如果某个库内容频繁变更,可以使用load方法来获取最新的内容。
这里有一个load使用方法的例子。将load方法放置在最顶端,将文件路径作为参数传给它。
load 'test_library.rb'
例如,当上例中的module定义在不同文件中时,就可以使用load来引入该方法。
#File: log.rb
module Log
def class_type
"This class is of type: #{self.class}"
end
end
#File: test.rb
load 'log.rb'
class TestClass
include Log
# ...
end
require
require可以用来加载库,并且避免进行多次加载。如果尝试require已经require过的库时会返回false。通常情况下,当需要引入其他文件中的内容时,使用require。
注意:
- 它会记录库是否已经被引用;
- 库名不需要.rb扩展名
以下是使用require的例子,将其放置于文件最顶端。
require 'test_library'
extend
当使用extend代替include时,模块中的方法以类方法而非实例方法的形式被插入类中。
下例展示extend方法的用法
module Log
def class_type
"This class is of type: #{self.class}"
end
end
class TestClass
extend Log
# ...
end
tc = TestClass.class_type
puts tc
打印结果:”This class is of type: TestClass”
在类中使用extend时,如果像使用include时一样将类实例化之后调用class_type方法,将会返回NoMethodError的异常。再次强调,extend会将模块中的方法作为类方法mixin进来!