159

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
  • 16,978
  • 8
  • 56
  • 70
Jeremy Smith
  • 14,177
  • 18
  • 66
  • 114

4 Answers4

271

What you posted should work perfectly:

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

Foo::CONSTANT_NAME
# => ["a", "b", "c"]
Dylan Markow
  • 120,567
  • 26
  • 279
  • 199
  • 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
48

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
  • 73,409
  • 36
  • 162
  • 195
47

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
  • 8,846
  • 8
  • 66
  • 80
18

Is there a way to access Foo::CONSTANT_NAME?

Yes, there is:

Foo::CONSTANT_NAME
Jörg W Mittag
  • 351,196
  • 74
  • 424
  • 630
  • 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? – Saikat Jun 24 '16 at 16:46