Jeremy Smith
Jeremy Smith

Reputation: 15069

Accessing a class's constants

When I have the following:

class Foo
   CONSTANT_NAME = ["a", "b", "c"]

  ...
end

Is there a way to access with Foo::CONSTANT_NAME or do I have to make a class method to access the value?

Upvotes: 175

Views: 95006

Answers (4)

aidan
aidan

Reputation: 9576

Some alternatives:

class Foo
  MY_CONSTANT = "hello"
end

Foo::MY_CONSTANT
# => "hello"

Foo.const_get :MY_CONSTANT
# => "hello"

x = Foo.new
x.class::MY_CONSTANT
# => "hello"

x.class.const_defined? :MY_CONSTANT
# => true

x.class.const_get :MY_CONSTANT
# => "hello"

Upvotes: 58

maček
maček

Reputation: 77778

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
  end
end

Foo.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

Upvotes: 52

Jörg W Mittag
Jörg W Mittag

Reputation: 369430

Is there a way to access Foo::CONSTANT_NAME?

Yes, there is:

Foo::CONSTANT_NAME

Upvotes: 18

Dylan Markow
Dylan Markow

Reputation: 124419

What you posted should work perfectly:

class Foo
  CONSTANT_NAME = ["a", "b", "c"]
end

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

Upvotes: 282

Related Questions