tawheed
tawheed

Reputation: 5821

Accessing constants outside a class

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?

Upvotes: 6

Views: 3309

Answers (1)

Alex Wayne
Alex Wayne

Reputation: 187272

Because an instance object and a class object are not the same thing. The namespace exists on the class object, and does not exist on the instance.

You can, however, ask the instance for it's class, then drill into that.

puts obj.class::CONST

Upvotes: 16

Related Questions