Accessing a class's constants

后端 未结 4 838
一个人的身影
一个人的身影 2020-12-24 00:00

When I have the following:

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

  ...
end

Is there a way to access with Foo::CONSTANT_

4条回答
  •  萌比男神i
    2020-12-24 00:23

    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"
    

提交回复
热议问题