包含模块和嵌入模块有什么区别?
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 代码。 如何从 Superman 类中调用flap_wings? 是否可以从类内部调用实例方法? 包含模块和嵌入模块有什么区别? 为什么以及何时应该这样做?
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
Hi I saw some ruby code which I couldn't understand. How do you call flap_wings from within the Superman class? Is it possible to call an instance method from within the class? What is the difference between including modules and embedding modules? Why and when should you do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我假设当您说嵌入模块时,您的意思是示例中的“Fly”模块嵌入在“Superpower”中。
如果是这样的话,我会将其称为嵌套模块。 我唯一使用嵌套模块的时候是嵌套模块专门处理主模块时,这样 Fly 中的代码与 Superpower 直接相关,但为了方便和可读性而分开。
您可以简单地使用嵌套模块的方法,只需首先包含 superpower,然后再包含 Fly,如下所示:
详细信息在 此博客。
I'm assuming that when you say embedding a module you mean the "Fly" module from your example is embedded in "Superpower".
If that is the case, I would call it a nested module. The only time I would use a Nested Module is when the nested module deals specifically with the main module, such that the code in Fly is directly correlated to Superpower, but are separated for convenience and readability.
You can use the nested module's methods simply by including superpower first, then fly second, like so:
The details are described further on this blog.
您需要阅读有关 mixins 的文档,这是解决 Ruby 仅具有单一继承这一事实的一种方法。 通过将给定模块 A 包含在类 B 中,A 中的所有模块方法都可用,就好像它们实际上是类 B 的一部分一样。
这意味着调用
turn_invisible
与For
flap_wings 一样简单
因为它位于另一个命名空间中,所以可能很简单:但我还没有尝试完成您的代码并“运行”它。
Mixin 的解释此处 和那里。
You want to read the documentation on mixins which are a way to workaround the fact that Ruby has only single inheritance. By including a given module A in a class B, all the modules methods in A are available as if they were actually part of class B.
That means that calling
turn_invisible
is as easy asFor
flap_wings
as it is in another namespace, it may be as easy as:but I haven't not tried to complete your code and "run" it.
Mixins are explained here and there.