了解Ruby模块的行为

Ray*_*oen 4 ruby scope module

所以我刚刚开始编写一些Ruby,虽然我理解模块是如何工作的,但以下行为仍然让我失望.

module ModuleA
    def a_greet
        'Hello from module A'
    end
end


module ModuleB
    def b_greet
        'Hello from module B'
    end
end


include ModuleA
include ModuleB

# WHY DOES THIS WORK !!!!!
p ModuleA.b_greet
Run Code Online (Sandbox Code Playgroud)

我知道模块中的函数可以在没有指定的情况下调用Module.,并且我永远不会以这种方式编写代码,但我不明白为什么在明确说明ModuleA时可以调用ModuleB中包含的方法?

Ser*_*sev 7

等等,还有更多:

"Why does this work?".b_greet # => "Hello from module B"
Run Code Online (Sandbox Code Playgroud)

您将这些模块包含在顶级对象中main.它是一个特殊的对象:它上面定义的所有方法都可用于所有对象(参见上面的行,现在有b_greet方法String).ModuleA也是一个对象,因此,当你包含时ModuleB,ModuleA获取它的方法.如果将这些模块包含在常规类/对象中,则不会获得此"共享"行为.