如何使用Ruby检查IniParse.parse中是否存在节
在阅读之前,如何检查是否存在如何使用Ruby检查IniParse.parse中是否存在节,ruby,ruby-on-rails-3,Ruby,Ruby On Rails 3,在阅读之前,如何检查是否存在conf['DEFAULT']?您可以用棍子戳它: require 'iniparse' conf = IniParse.parse(File.read('my.conf')) 或者你可以更聪明一点: if (conf.key?('DEFAULT')) # Congratulations, there's something there else # Uh-oh, it's missing. Panic? end 我这样做了:除非conf['agent'
conf['DEFAULT']
?您可以用棍子戳它:
require 'iniparse'
conf = IniParse.parse(File.read('my.conf'))
或者你可以更聪明一点:
if (conf.key?('DEFAULT'))
# Congratulations, there's something there
else
# Uh-oh, it's missing. Panic?
end
我这样做了:除非conf['agent'].nil?在Ruby中,逻辑上唯一错误的是
nil
和false
,所以除非你期望conf['agent']
是字面上的false
,否则你可以做if-conf['agent']
,并确信它会工作。由于您可能正在查找字符串、哈希结构或数组,false
无论如何都不是您感兴趣的东西。
case (conf['DEFAULT'])
when Hash
# Great, that's what I was expecting!
when nil
# Uh-oh, it's missing. Panic?
else
# That's not what I was expecting.
end