Include
如下例当你Include一个模块到某个类时, 相当于把模块中定义的方法插入到类中。它允许使用 mixin。它用来 DRY 你的代码, 避免重复。例如, 当你有多个类时, 需要相同的函数时, 可以把函数定义到module中, 进行include。 下例假设模块Log和类TestClass在相同的.rb文件。如果它们存在于多个文件, 则需要使用 load 或 require 导入文件。
1
2
3
4
5
6
7
8
9
10
11module 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
Extend