168

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?

4 Answers 4

279

What you posted should work perfectly:

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

Foo::CONSTANT_NAME
# => ["a", "b", "c"]
6
  • 2
    Hmm, I must have mistyped when I tested earlier. Ooops :) Jun 21, 2011 at 17:51
  • 12
    for this to truly be a constant, don't forget to add a .freeze on the end of the value! CONSTANT_NAME = ["a", "b", "c"].freeze
    – mutexkid
    Oct 8, 2015 at 15:57
  • 7
    Always mix up :: and . ;)
    – Nick
    May 1, 2017 at 22:17
  • Things are hard to spot when uppercased ;) May 22, 2019 at 19:39
  • 1
    @wuarmin I believe that :: is for module/class level thing (so in the above, CONSTANT_NAME is a class "static" property). You'd also use it for module namespacing eg ActiveRecord::Base. The . is used for instance properties and methods (eg Foo.new). Although I believe you can use . to call static methods... There is a lot of discussion about it on SO.. Eg: stackoverflow.com/a/11043499/224707
    – Nick
    Apr 7, 2021 at 13:41
52

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"
50

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
18

Is there a way to access Foo::CONSTANT_NAME?

Yes, there is:

Foo::CONSTANT_NAME
1
  • When i am trying to access it, i am having below warning. warning: already initialized constant TestData::CONSTANT_VAR This variable is not initialized anywhere else. Why i am having this warning?
    – ASM
    Jun 24, 2016 at 16:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.