Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing constants outside a class

Tags:

oop

ruby

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?

like image 874
tawheed Avatar asked Feb 14 '13 01:02

tawheed


1 Answers

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
like image 102
Alex Wayne Avatar answered Sep 20 '22 23:09

Alex Wayne