Bearish_Boring_dude
Bearish_Boring_dude

Reputation: 627

How to get the empty hash to raise errors?

I have the following lines of code:

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

How can I error out what was the empty key that was causing the error?

Upvotes: 2

Views: 701

Answers (2)

SztupY
SztupY

Reputation: 10546

You can set a proc to the hash that will be executed when a key is not found (don't forget to set the origin value back after using this hash, or to duplicate the original hash):

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

For your example:

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

but probably you don't need an Exception anyway:

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

Upvotes: 1

Thomas
Thomas

Reputation: 182000

Unless you want to pass a state-changing block to the any? method, which is bad practice, you'll need to loop over the keys with each:

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

Upvotes: 2

Related Questions