Ruby中的include和extend有什么区别?
时间:2020-03-06 14:57:44 来源:igfitidea点击:
只是引起我对Ruby元编程的关注。 mixin /模块总是设法使我感到困惑。
- 包括:将指定的模块方法混合为目标类中的实例方法
- 扩展:将指定的模块方法作为目标类中的类方法进行混合
那么主要的区别就是这样吗?还是更大的龙潜伏了?
例如
module ReusableModule def module_method puts "Module Method: Hi there!" end end class ClassThatIncludes include ReusableModule end class ClassThatExtends extend ReusableModule end puts "Include" ClassThatIncludes.new.module_method # "Module Method: Hi there!" puts "Extend" ClassThatExtends.module_method # "Module Method: Hi there!"
解决方案
没错
在幕后,包含实际上是append_features的别名,该别名(来自文档):
Ruby's default implementation is to add the constants, methods, and module variables of this module to aModule if this module has not already been added to aModule or one of its ancestors.
你说的是对的。但是,还有更多的东西。
如果我们具有类Klazz和模块Mod,则在Klazz中包含Mod可以使Klazz实例访问Mod方法。或者,我们可以使用Mod扩展Klazz,从而使类Klazz能够访问Mod的方法。但是你也可以使用o.extend Mod扩展任意对象。在这种情况下,即使所有其他对象与" o"具有相同的类,单个对象也会获得" Mod"的方法。