Accessing a class’ constant variables

Accessing a class’ constant variables

Add Comment


  • 3 Answer(s)

    Constant variables: 

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

    Answered on January 11, 2019.
    Add Comment

    Using class  contains in global: 

    class Foo
      MY_CONSTANT = "hello"
     
      def bar
        MY_CONSTANT
      end
    end
     
    Foo.new.bar #=> hello
    

    Class, prefix it with the class name

    Foo::MY_CONSTANT #=> hello
    

    Answered on January 11, 2019.
    Add Comment

    Alternative solution:

    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"
    

    Answered on January 11, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.