我會做這樣的事情:
begin
@param_info.fetch(:drug).fetch(:name)
rescue KeyError
# handle key not found
end
你可以做一個單一的功能:
def param_info_key(info, key1, key2)
info.fetch(key1).fetch(key2)
rescue KeyError
nil
end
param_info_key({}, :a, :b) # nil
param_info_key({a: {}}, :a, :b) # nil
param_info_key({a: {b: "foo"}}, :a, :b) # "foo"
Sa mple:
irb(main):001:0> s = {}
=> {}
irb(main):002:0> begin
irb(main):003:1* s.fetch(:foo).fetch(:bar)
irb(main):004:1> rescue KeyError
irb(main):005:1> puts "Key not found"
irb(main):006:1> end
Key not found
=> nil
我真的很喜歡多麼簡單,這是,但它仍然給我一個錯誤:關鍵未找到:「drddsug」(我把隨機字符測試) – Rob
@Rob,請看我更新的答案。這將更加霧! – vee
完美!謝謝 – Rob