Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
这是一个简单的,我希望。在以下示例中,如何检查是否已定义常量?
#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)
CONST = 2 unless defined? CONST
有关出色操作员的更多信息,请参见此处defined?。
defined?
PS而且在未来我猜你会想要var ||= 1而不是var = var||1.
var ||= 1
var = var||1
常量定义?API
pry> User.const_defined?("PER_PAGE") => true pry> User.const_defined?("PER_PAGE123") => false
CONST ||= :default_value
以上在 ruby 1.9.3 上对我有用,但在 1.8 上失败了……现在 1.8 已经很古老了。