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)
3 个解决方案
#1
109
CONST = 2 unless defined? CONST
See here for more about awesome defined?
operator.
在这里看到更多关于可怕的定义吗?操作符。
P.S. And in the future I guess you'll want var ||= 1
instead of var = var||1
.
顺便说一下,我猜你以后会想要var|| = 1而不是var = var||1。
#2
12
const_defined? API pry> User.const_defined?("PER_PAGE") => true pry> User.const_defined?("PER_PAGE123") => false
const_defined吗?API pry> User.const_defined?("PER_PAGE") => true pry> User.const_defined?("PER_PAGE123") => false
#3
3
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现在已经很古老了。
#1
109
CONST = 2 unless defined? CONST
See here for more about awesome defined?
operator.
在这里看到更多关于可怕的定义吗?操作符。
P.S. And in the future I guess you'll want var ||= 1
instead of var = var||1
.
顺便说一下,我猜你以后会想要var|| = 1而不是var = var||1。
#2
12
const_defined? API pry> User.const_defined?("PER_PAGE") => true pry> User.const_defined?("PER_PAGE123") => false
const_defined吗?API pry> User.const_defined?("PER_PAGE") => true pry> User.const_defined?("PER_PAGE123") => false
#3
3
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现在已经很古老了。