加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 22:55:15 所属栏目:百科 来源:网络整理
导读:从 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 mod
从 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?

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读