在Ruby中,我发现为了名称空间,将类放在模块中是很有用的.我还发现可以在类中放置模块.但我不明白你为什么这么做.
模块通常被混合到类中,对吗?那么,what would be the purpose of defining a module inside a class?
在Ruby中,我发现为了名称空间,将类放在模块中是很有用的.我还发现可以在类中放置模块.但我不明白你为什么这么做.
模块通常被混合到类中,对吗?那么,what would be the purpose of defining a module inside a class?
我们可以在编写类人猿代码时使用它:
class DrugDealer
module Drug
def happy?; true; end
end
def approach(victim)
victim.extend Drug
end
end
o = Object.new
DrugDealer.new.approach(o)
o.happy? # => true
在现实世界中更实际的另一个例子是,只有子类才能应用mixin.
当一个事物的大约facets个方面应用于某些子类,而其他方面应用于其他子类,而这些方面的应用方式没有足够的顺序来为清晰的类层次 struct (树)让路时,这很有用.想想多重继承吧!一个简单的例子:
class Person
def handshake
:sloppy
end
def mind_contents
:spam
end
module Proper
def handshake
:firm
end
end
module Clever
def mind_contents
:theories
end
end
end
class Professor < Person
include Proper
include Clever
# ...
end
等等当使用得当时,感觉不错.即使是超级调用和构造函数(我在这里没有定义任何构造函数)也会以我希望的方式在所有的mixin和类中流动.