module Superpower
# instance method
def turn_invisible
...
end
# module method
def Superpower.turn_into_toad
...
end
module Fly
def flap_wings
...
end
end
end
Class Superman
include Superpower
...
def run_away
# how to call flap_wings?
# how to call turn_invisible?
end
def see_bad_guys(bad_guy = lex_luthor)
#is this correct?
Superpower.turn_into_toad(bad_guy)
end
end嗨,我看到了一些我看不懂的ruby代码。如何从超人类中调用flap_wings?是否可以从类中调用实例方法?包含模块和嵌入模块有什么区别?为什么以及什么时候应该这样做?
发布于 2009-01-19 23:29:12
我假设当你说嵌入一个模块时,你指的是你例子中的"Fly“模块嵌入到"Superpower”中。
如果是这样的话,我会称它为嵌套模块。只有当嵌套模块专门处理主模块时,我才会使用嵌套模块,这样Fly中的代码与超能力直接相关,但为了方便和可读性而分开。
您可以简单地使用嵌套模块的方法,只需先包含超能力,然后再飞,如下所示:
Class Superman
include Superpower
include Fly
# ...
end有关详细信息,请参阅this blog。
发布于 2009-01-19 23:28:34
你想要阅读关于混入的文档,这是一种解决Ruby只有一个继承的事实的方法。通过将给定模块A包含在类B中,A中的所有模块方法都是可用的,就像它们实际上是类B的一部分一样。
这意味着调用turn_invisible就像
def run_away
turn_invisible
end对于flap_wings来说,因为它在另一个名称空间中,所以它可能像下面这样简单:
def fly_away
Fly.flap_wings
end但是我并没有试着完成你的代码并“运行”它。
Mixin被解释为here和there。
https://stackoverflow.com/questions/459590
复制相似问题