Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 包含模块和嵌入模块之间有什么区别?_Ruby_Module_Mixins_Oop - Fatal编程技术网

Ruby 包含模块和嵌入模块之间有什么区别?

Ruby 包含模块和嵌入模块之间有什么区别?,ruby,module,mixins,oop,Ruby,Module,Mixins,Oop,嗨,我看到一些我不懂的ruby代码。你怎么称呼超人班里的翅膀?是否可以从类中调用实例方法?包含模块和嵌入模块之间有什么区别?为什么以及什么时候应该这样做?您想阅读关于mixin的文档,这是解决Ruby只有单一继承这一事实的一种方法。通过在类B中包含给定的模块a,a中的所有模块方法都可用,就好像它们实际上是类B的一部分一样 这意味着调用turn\u invisible与 module Superpower # instance method def turn_invisible

嗨,我看到一些我不懂的ruby代码。你怎么称呼超人班里的翅膀?是否可以从类中调用实例方法?包含模块和嵌入模块之间有什么区别?为什么以及什么时候应该这样做?

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

这意味着调用
turn\u invisible

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
对于
flap_wings
,由于它位于另一个名称空间中,它可能很容易:

def run_away
  turn_invisible
end
但我还没有尝试完成您的代码并“运行”它


mixin已经解释过了。

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

这意味着调用
turn\u invisible

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
对于
flap_wings
,由于它位于另一个名称空间中,它可能很容易:

def run_away
  turn_invisible
end
但我还没有尝试完成您的代码并“运行”它


mixin已经解释过了。

我假设当你说嵌入一个模块时,你的例子中的“Fly”模块嵌入到了“Superpower”中

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

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

def fly_away
  Fly.flap_wings
end

细节将在后面进一步描述。

我假设当你说嵌入一个模块时,你的意思是你例子中的“飞”模块嵌入到了“超级大国”中

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

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

def fly_away
  Fly.flap_wings
end

详细信息将在后面进一步描述。

如果您不介意,我添加了一些更精确的标记。如果您不介意,我添加了一些更精确的标记。