6

When I want to access the constant CONST in class Test in

class Test
  CONST = 7
end

from outside of the class, I have to do this:

puts Test::CONST

Why do I get an error when I do this?

puts obj::CONST

If obj is an object of the Test class, why do I get an error if I try to access the constant through the object?

4

1 回答 1

16

因为实例对象和类对象不是一回事。命名空间存在于类对象上,不存在于实例上。

但是,您可以向实例询问它的类,然后深入研究。

puts obj.class::CONST
于 2013-02-14T01:30:00.157 回答