Access to constants outside the class

When I want to access a constant CONSTin a class Testin

class Test
  CONST = 7
end

from outside the class, I have to do this:

puts Test::CONST

Why am I getting an error when I do this?

puts obj::CONST

If it objis an object of a class Test, why do I get an error if I try to access a constant through an object?

+5
source share
1 answer

Because the instance object and the class object are not the same thing. The namespace exists in the class object and does not exist in the instance.

However, you can request an instance for this class, then expand it.

puts obj.class::CONST
+15
source

All Articles