Ruby中包含和扩展有什么区别? [英] What is the difference between include and extend in Ruby?
问题描述
让我了解Ruby元编程。 mixin / modules总是让我困惑。
Just getting my head around Ruby metaprogramming. The mixin/modules always manage to confuse me.
- include :在指定的模块方法中混合使用目标类中的实例方法
- 扩展:将指定模块方法混合为目标类中的类方法
- include: mixes in specified module methods as instance methods in the target class
- extend: mixes in specified module methods as class methods in the target class
这是主要区别还是潜伏着更大的龙?
例如
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!"
推荐答案
你所说的是正确的。但是还有更多。
What you have said is correct. However there is more to it than that.
如果你有一个类 Klazz
和模块 Mod
,包括 Mod
在 Klazz
中提供 Klazz的实例
访问 Mod
的方法。或者您可以使用 Mod
扩展 Klazz
,并提供类 Klazz
访问 Mod
的方法。但您也可以使用 o.extend Mod
扩展任意对象。在这种情况下,单个对象获得 Mod
的方法,即使与 o
具有相同类别的所有其他对象也不。
If you have a class Klazz
and module Mod
, including Mod
in Klazz
gives instances of Klazz
access to Mod
's methods. Or you can extend Klazz
with Mod
giving the class Klazz
access to Mod
's methods. But also you can extend an arbitrary object with o.extend Mod
. In this case the individual object gets Mod
's methods even though all other objects with the same class as o
do not.
这篇关于Ruby中包含和扩展有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!