包含模块如何影响范围?具体地,在这个例子中:Ruby类,包含和范围
module ModuleA
class ClassA
def initialize
puts "test passed"
end
end
end
module ModuleB
include ModuleA
# test 1
C = ClassA.new
class ClassB
def initialize
c = ClassA.new
end
end
end
# test 2 and 3 fail without this
#include ModuleB
module ModuleC
# this doesn't help
include ModuleB
# test 2
ClassB.new
# test 3
ModuleB::ClassB.new
end
试验1工作正常,但试验2和测试3失败而不注释的import ModuleB
。
- 为什么范围
ClassA
的ModuleB
(测试1)内而不是在ClassB
? - 为什么
import ModuleB
将ClassA
纳入ClassB
的范围?
对于** test2 **和** test3 **来说,您需要在'ClassB'内部包含'ModuleA',或者让'ClassB
derp