我有以下代码行:
keys = [:a, :b, :c, :d, :e, :f, :g]
if keys.any? do |key|
node[:app][:alphabets][key].empty?
error << " "
end
unless error.empty?
raise error
end
我怎样才能找出导致错误的空键是什么?
我有以下代码行:
keys = [:a, :b, :c, :d, :e, :f, :g]
if keys.any? do |key|
node[:app][:alphabets][key].empty?
error << " "
end
unless error.empty?
raise error
end
我怎样才能找出导致错误的空键是什么?
除非您想将状态更改块传递给该any?
方法(这是不好的做法),否则您需要使用以下命令循环键each
:
keys.each do |key|
error << key if node[:app][:alphabets][key].empty?
end
您可以将 proc 设置为未找到键时将执行的哈希(不要忘记在使用此哈希后将原始值设置回原值,或复制原始哈希):
irb(main):017:0> a = {:a => 1, :b => 2}
irb(main):018:0> a.default_proc = lambda{|h,v| raise Exception.exception(v)}
irb(main):019:0> a[:a]
=> 1
irb(main):020:0> a[:b]
=> 2
irb(main):021:0> a[:c]
Exception: :c
irb(main):022:0> a.default_proc = nil
对于您的示例:
keys = [:a, :b, :c, :d, :e, :f, :g]
alphabets = node[:app][:alphabets].dup
alphabets.default_proc = lambda{|h,v| raise Exception.exception(v)}
if keys.any? {|key| alphabets[key].empty? } then
# do stuff
end
但可能无论如何你都不需要异常:
keys = [:a, :b, :c, :d, :e, :f, :g]
alphabets = node[:app][:alphabets].dup
missing = nil
alphabets.default_proc = lambda{|h,v| missing = v }
if keys.any? {|key| alphabets[key].empty? } then
# do stuff
else
# value inside missing was missing
end