Ruby中的’include’和’prepend’有什么区别?

Module

Module#append_features(mod) → mod => When this module is included in another,Ruby calls append_features in this module,passing it the receiving module in mod. Ruby’s default implementation is to add the constants,methods,and module variables of this module to mod if this module has not already been added to mod or one of its ancestors.

Module#prepend_features(mod) → mod => When this module is prepended in another,Ruby calls prepend_features in this module,passing it the receiving module in mod. Ruby’s default implementation is to overlay the constants,and module variables of this module to mod if this module has not already been added to mod or one of its ancestors.

任何人都可以帮助我了解以下问题:

>除了认值之外,Module的哪些功能被定义为附加和前缀?
>他们的功能差异如何?
>何时使用append_features和prepend_features?
>以上两条粗线之间有什么区别?

解决方法

>模块的哪些特征被定义为附加和前缀?

如您所引用的文字所述:

the constants,and module variables

>他们的功能差异如何?

将混合模块的方法添加到传递的模块(类)中.区别在于这些方法的查找顺序,如果目标类已经定义了它们:

include的行为就好像目标类继承了mixed-in模块:

module FooBar
  def say
    puts "2 - Module"
  end
end

class Foo
  include FooBar

  def say
    puts "1 - Implementing Class"
    super
  end
end

Foo.new.say # =>
            # 1 - Implementing Class
            # 2 - Module

prepend使得混合模块中的方法“更强”,并先执行它们:

module FooBar
  def say
    puts "2 - Module"
    super
  end
end

class Foo
  prepend FooBar

  def say
    puts "1 - Implementing Class"
  end
end

Foo.new.say # =>
            # 2 - Module
            # 1 - Implementing Class

这个例子从这里撕下来:http://blog.crowdint.com/2012/11/05/3-killer-features-that-are-coming-on-ruby-2-0.html

>何时使用append_features和prepend_features?

当您想要在方法查找链的末尾保留目标模块(类)的方法时,请使用前端.

通过搜索SO,可以找到一些现实的例子,包括ruby,module和prepend:

> Overriding method by another defined in module
> When monkey patching a method,can you call the overridden method from the new implementation?
> Ruby: Module,Mixins and Blocks confusing?

(注意:我只提到方法,因为它们是最简单的图形,当涉及到继承和混合,但同样适用于其他功能.)

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...