微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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?

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐