在上周的提示中,我们了解了祖先的情况。这为我们学习在类中使用模块中的代码的三种方式做了准备。本周,我们将讨论这些方法中最常见的一种。 include.
我们可以看一个使用include ,将一个模块的方法包含在一个类中的例子:
module ExampleModule
def example_method
"This is defined in the module we're including"
end
end
class ExampleClass
include ExampleModule
end
ExampleClass.new.example_method
=> "This is defined in the module we're including"
当我们include ExampleModule ,或include 任何模块或类时,实际发生的情况是,这个模块或类将被直接插入祖先链中,而这个类是include的:
ExampleClass.ancestors
=> [ExampleClass, ExampleModule, Object, Kernel, BasicObject]
正如我们上周所学到的,这意味着Ruby将首先寻找定义在ExampleClass 上的方法,如果它没有定义在那里,它将继续遍历祖先的列表,接下来寻找ExampleModule 。
这意味着使用include 给我们提供了一个有用的属性,即能够轻松地覆盖在一个包含的模块中定义的方法:
module ExampleModule
def example_method
"This is defined in the module we're including"
end
end
class ExampleClass
include ExampleModule
def example_method
"This is defined in ExampleClass itself"
end
end
ExampleClass.new.example_method
=> "This is defined in ExampleClass itself"
如果我们习惯于使用include ,我们可能会对这种覆盖的操作有一个直观的理解。希望现在有了关于ancestors 的背景,我们可以明白为什么会发生这种情况。在接下来的几周里,我们将围绕另外两种使用模块或类的代码的方法进行提示:extend 和prepend 。