ruby 检查常量是否已定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10171978/
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-06 05:00:52  来源:igfitidea点击:

Check if a constant is already defined

rubyconstants

提问by peter

This is a simple one, I hope. How do I check, in the following example, if a constant is already defined?

这是一个简单的,我希望。在下面的示例中,如何检查常量是否已定义?

#this works
var = var||1
puts var
var = var||2
puts var

#this doesn't
CONST = CONST||1
puts CONST
CONST = CONST||2
puts CONST

=> 1
   1
   uninitialized constant CONST (NameError)

回答by jibiel

CONST = 2 unless defined? CONST

See herefor more about awesome defined?operator.

请参阅此处了解有关 awesomedefined?运算符的更多信息。

P.S. And in the future I guess you'll want var ||= 1instead of var = var||1.

PS,将来我想你会想要var ||= 1而不是var = var||1.

回答by rusllonrails

const_defined? API

const_定义?应用程序接口

pry> User.const_defined?("PER_PAGE")
=> true
pry> User.const_defined?("PER_PAGE123")
=> false

回答by akostadinov

CONST ||= :default_value

the above works for me on ruby 1.9.3 but fails on 1.8... well 1.8 is ancient now.

以上在 ruby​​ 1.9.3 上对我有效,但在 1.8 上失败......现在 1.8 很古老了。