【问题标题】:What is the difference betwen including modules and embedding modules?包括模块和嵌入模块有什么区别?
【发布时间】:2010-10-02 08:31:57
【问题描述】:
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?是否可以从类中调用实例方法?包含模块和嵌入模块有什么区别?为什么以及何时应该这样做?

【问题讨论】:

  • 如果你不介意的话,我添加了一些更精确的标签。

标签: ruby module mixins oop


【解决方案1】:

我假设当您说嵌入模块时,您的示例中的“Fly”模块嵌入在“Superpower”中。

如果是这样的话,我会称它为嵌套模块。我唯一会使用嵌套模块的时候是嵌套模块专门处理主模块,这样 Fly 中的代码与 Superpower 直接相关,但为了方便和可读性而分开。

您可以使用嵌套模块的方法,只需先包含 superpower,然后再包含 fly,如下所示:

Class Superman
    include Superpower
    include Fly
    # ...
end

详情请参阅this blog

【讨论】:

    【解决方案2】:

    您想阅读有关 mixins 的文档,这是一种解决 Ruby 只有单一继承这一事实的方法。通过在 B 类中包含给定的模块 A,A 中的所有模块方法都可以使用,就好像它们实际上是 B 类的一部分一样。

    这意味着调用turn_invisible 就像

    def run_away
      turn_invisible
    end
    

    对于flap_wings,因为它在另一个命名空间中,它可能很简单:

    def fly_away
      Fly.flap_wings
    end
    

    但我还没有尝试完成您的代码并“运行”它。

    Mixins 解释 herethere

    【讨论】:

      猜你喜欢
      • 2011-04-10
      • 1970-01-01
      • 2019-09-21
      • 2015-11-25
      • 2011-12-18
      • 2020-03-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多