Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

Ruby Constants and Nested Classes

I'm trying to understand what the following will produce. According to IRHG, this code will return A1.

IRHG says: Constants are search for first outside the class. If not found outside, then searched inside the class.

But I've got the following message in Ruby 1.8.7

uninitialized constant A3::B3::C3::Const (NameError)

Would you please help me to understand this correctly?

class A1
    Const = "A1"
end
class A2 < A1
end
class A3 < A2
    #Const = "A3"
    class B1
    end
    class B2 < B1
    end
    class B3 < B2
        class C1
        end
        class C2 < C1
        end
        class C3 < C2
            p Const
        end
    end
end
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In your case C3 class isn't inherit from A3 class. A3 class is only a namespace for C3.

A3::B3::C3.superclass
#=> A3::B3::C2
A3::B3::C3.superclass.superclass
#=> A3::B3::C1
A3::B3::C3.superclass.superclass.superclass
#=> Object
# or you can look A3::B3::C3.ancestors for full map

While

A3.superclass
#=> A2
A2.superclass
#=> A1

So when you puts one class inside of another you don't inherit but nest classes


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...