Ruby中的"include"和"prepend"有什么区别? [英] What is the difference between 'include' and 'prepend' in Ruby?
问题描述
从模块
Module#append_features(mod)→mod =>当此模块包含在另一个模块中时,Ruby会在此模块中调用append_features,并将其传递给mod中的接收模块. Ruby的默认实现是 添加 (如果尚未将该模块的常量,方法和模块变量添加到mod或它的祖先之一).
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 =>当此模块附加在另一个模块中时,Ruby会在此模块中调用prepend_features,并将其传递给mod中的接收模块. Ruby的默认实现是 要覆盖 (如果尚未将此模块添加到mod或其祖先之一),以将该模块的常量,方法和模块变量进行修改.
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, methods, and module variables of this module to mod if this module has not already been added to mod or one of its ancestors.
任何人都可以帮助我理解以下问题:
Can anyone help me to understand the below questions:
-
除了默认设置外,
Module
的哪些功能还定义为append
和prepend
?
What more features of
Module
are defined asappend
andprepend
except those default?
它们在功能上有何不同?
How they differ functionally?
何时使用append_features
和何时使用prepend_features
?
上述两条粗线之间有什么区别?
what is the difference between two bold lines as above?
推荐答案
- 模块的哪些功能定义为追加和前置?
- 它们在功能上有何不同?
根据您引用的文字中的说明:
As specified in the text you quoted:
常量,方法和模块变量
the constants, methods, and module variables
将混合模块的两种添加方法都添加到传递的模块(类)中.如果目标类已经定义了这些方法,则区别在于这些方法的查找顺序:
Both add methods of the mixed-in module to the passed module (class). The difference is in the lookup order of these methods, in case that the target class already has them defined:
include
的行为就像目标类继承了混合模块:
include
behaves as if the target class inherited mixed-in module:
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
使混合模块中的方法更强"并首先执行它们:
prepend
makes the methods from the mixed in module "stronger" and executes them first:
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