Why there is an error in the following example?
class ClassA
class ClassB
end
class ClassC
def test
ClassB.new
end
end
end
p ClassA::ClassC.new.test # => #<ClassA::ClassB:0x0000010103f860>
class ClassA
class ClassD
def test
ClassB.new
end
end
end
p ClassA::ClassD.new.test # => #<ClassA::ClassB:0x0000010103f010>
class ClassA::ClassE
def test
ClassB.new
end
end
p ClassA::ClassE.new.test # => NameError: uninitialized constant ClassA::ClassE::ClassB
Is there another way to create ClassE, not by typing class ClassA; class ClassE?
Well, yes, if you define your test method to return
ClassA::ClassB.new🙂You could also play around with
const_missingso that it callsClassA.const_get.Otherwise
ClassBis not in the current scope, which at that point is onlyClassA::ClassEandObject. When you first openClassA, thenClassE, the lookup forClassBis done first inClassA::ClassE, then inClassA(where it is found) and would also look inObject.