Accessing a class's constants

Ruby on-RailsRubyConstants

Ruby on-Rails Problem Overview


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?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

What you posted should work perfectly:

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

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

Solution 2 - Ruby on-Rails

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

Solution 3 - Ruby on-Rails

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"

Solution 4 - Ruby on-Rails

>Is there a way to access Foo::CONSTANT_NAME?

Yes, there is:

Foo::CONSTANT_NAME

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJeremy SmithView Question on Stackoverflow
Solution 1 - Ruby on-RailsDylan MarkowView Answer on Stackoverflow
Solution 2 - Ruby on-RailsmačekView Answer on Stackoverflow
Solution 3 - Ruby on-RailsaidanView Answer on Stackoverflow
Solution 4 - Ruby on-RailsJörg W MittagView Answer on Stackoverflow