如何获取空哈希以引发错误?

时间:2013-05-23 19:48:54

标签: ruby

我有以下几行代码:

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

如何判断导致错误的空键是什么?

2 个答案:

答案 0 :(得分:2)

除非您想将状态更改块传递给any?方法,这是不好的做法,否则您需要使用each循环键:

keys.each do |key|
  error << key if node[:app][:alphabets][key].empty?
end

答案 1 :(得分:1)

您可以将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

但是你可能还不需要Exception:

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
相关问题