prepend使用的语法介绍

85 阅读1分钟

我们将继续我们简短的本周提示系列,围绕使用模块中的代码,学习以下内容 prepend.上周,我们了解了 include以及它如何将一个模块直接插入到包含它的类之后的祖先链中。

prepend 使用与 相同的语法,但工作方式不同--它将一个模块直接插入到包含它的类include 之前的祖先链中。让我们看一看。

module ExampleModule
  def example_method
    "This is defined in the module we're prepending"
  end
end

class ExampleClass
  prepend ExampleModule
end

ExampleClass.new.example_method
=> "This is defined in the module we're prepending"

现在,如果我们看一下祖先链,我们会看到ExampleModule ExampleClass之前。这与我们上周看到的ExampleModule 继承 ExampleClass 的情况完全相反:

ExampleClass.ancestors
=> [ExampleModule, ExampleClass, Object, Kernel, BasicObject]

正如我们在[讨论祖先][祖先]时学到的,这意味着Ruby会首先寻找定义在ExampleModule 上的方法,如果它没有定义在那里,它将继续遍历祖先列表,接下来寻找ExampleClass (我们的类本身)。

这意味着使用prepend 将导致我们预置的模块上定义的方法比类本身定义的方法更多:

module ExampleModule
  def example_method
    "This is defined in ExampleModule, which we're prepending"
  end
end

class ExampleClass
  prepend ExampleModule

  def example_method
    "This is defined in ExampleClass itself"
  end
end

ExampleClass.new.example_method
=> "This is defined in ExampleModule, which we're prepending"

prepend 通常用于一个模块覆盖一个类中定义的方法的情况。这方面的例子可能是当一个模块需要在 方法中设置一些东西,但类本身的 方法并不调用 。模块中的 方法可以做它需要的任何设置,然后调用 来执行类的 方法。initialize initialize super initialize super initialize

我们下周将学习extend!