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
提问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
回答by rusllonrails
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 很古老了。

