Ruby-on-rails 访问类的常量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6427548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 01:26:52  来源:igfitidea点击:

Accessing a class's constants

ruby-on-railsrubyconstants

提问by Jeremy Smith

When I have the following:

当我有以下内容时:

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

  ...
end

Is there a way to access with Foo::CONSTANT_NAMEor do I have to make a class method to access the value?

有没有办法访问Foo::CONSTANT_NAME或我必须创建一个类方法来访问该值?

回答by Dylan Markow

What you posted should work perfectly:

您发布的内容应该可以完美运行:

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

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

回答by aidan

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"

回答by ma?ek

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

回答by J?rg W Mittag

Is there a way to access Foo::CONSTANT_NAME?

有办法访问Foo::CONSTANT_NAME吗?

Yes, there is:

就在这里:

Foo::CONSTANT_NAME