Accessing a class's constants Accessing a class's constants ruby ruby

Accessing a class's constants


What you posted should work perfectly:

class Foo  CONSTANT_NAME = ["a", "b", "c"]endFoo::CONSTANT_NAME# => ["a", "b", "c"]


If you're writing additional code within your class that contains the constant, you can treat it like a global.

class Foo  MY_CONSTANT = "hello"  def bar    MY_CONSTANT  endendFoo.new.bar #=> hello

If you're accessing the constant outside of the class, prefix it with the class name, followed by two colons

Foo::MY_CONSTANT  #=> hello


Some alternatives:

class Foo  MY_CONSTANT = "hello"endFoo::MY_CONSTANT# => "hello"Foo.const_get :MY_CONSTANT# => "hello"x = Foo.newx.class::MY_CONSTANT# => "hello"x.class.const_defined? :MY_CONSTANT# => truex.class.const_get :MY_CONSTANT# => "hello"