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?

Arslan Ali
  • 17,418
  • 8
  • 58
  • 76
Jeremy Smith
  • 14,727
  • 19
  • 67
  • 114

4 Answers4

279

What you posted should work perfectly:

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

Foo::CONSTANT_NAME
# => ["a", "b", "c"]
Dylan Markow
  • 123,080
  • 26
  • 284
  • 201
  • 2
    Hmm, I must have mistyped when I tested earlier. Ooops :) – Jeremy Smith Jun 21 '11 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 08 '15 at 15:57
  • 7
    Always mix up `::` and `.` ;) – Nick May 01 '17 at 22:17
  • Things are hard to spot when uppercased ;) – Michael Yin May 22 '19 at 19:39
  • @Nick what is the rule? when should I use `.` and when `::`? thx – wuarmin Apr 07 '21 at 09:29
  • 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: https://stackoverflow.com/a/11043499/224707 – Nick Apr 07 '21 at 13:41
51

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"
aidan
  • 9,310
  • 8
  • 68
  • 82
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
maček
  • 76,434
  • 37
  • 167
  • 198
18

Is there a way to access Foo::CONSTANT_NAME?

Yes, there is:

Foo::CONSTANT_NAME
Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
  • 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 '16 at 16:46