本文介绍了Ruby从内部类访问常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个类似的嵌套类:
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"]
**。但它不起作用( ..不是类/模块[TypeError])。我在做什么错?
**.. but it won't work ("..is not a class/module [TypeError]"). 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"
这篇关于Ruby从内部类访问常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!