问题
I have a nested class like so:
class Mammal
H = "Mammal"
class Human
H = "Human"
end
end
And I want to make an Human object and after access the Human's constant, like so:
human = Mammal::Human.new # makes an object successfully
puts human::H # does not work **
puts Mammal::Human::H # works ["Human"]
puts Mammal::H # works ["Mammal"]
**.. but it won't work ("..is not a class/module [TypeError]"). What am i doing wrong?
回答1:
What am I doing wrong?
You're trying to refer a constant from a wrong context. Constants are defined in class objects, not in instances. This works:
human = Mammal::Human.new
human.class.const_get(:H) # => "Human"
回答2:
Constants belong to classes, therefore constant resolution via the ::
operator only works with class objects, not with instances of a class.
With that said, you can do this:
human.class::H
Object#class
returns the object's class, relative to which you can resolve constants.
来源:https://stackoverflow.com/questions/14260931/ruby-accessing-constants-from-inner-class