检查是否已经定义了常量

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

#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)
44802 次浏览
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.

CONST ||= :default_value

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

const_defined? API

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