有时在处理 API 响应时,我最终会写这样的东西:
what_i_need = response["key"]["another key"]["another key 2"]
问题是,如果 "another key"
丢失,它会抛出错误。我不喜欢那样。如果 what_i_need
在过程中出现问题时出现 nil
,我会更开心。
是否有比以下更优雅的解决方案:
what_i_need = nil
begin
what_i_need = response["key"]["another key"]["another key 2"]
rescue Exception => e
end
我也考虑过猴子修补 NilClass 你尝试访问 nil["something"]
它会返回 nil
,但我不确定这是否是最好的方法如果可能的话,就去做吧。
最佳答案
使用Hash#fetch具有默认值。
h = {:a => 2}
h.fetch(:b,"not present")
# => "not present"
h.fetch(:a,"not present")
# => 2
如果没有默认值,它将抛出 KeyError
。
h = {:a => 2}
h.fetch(:b)
# ~> -:2:in `fetch': key not found: :b (KeyError)
但是对于嵌套的Hash
,你可以使用:
h = {:a => {:b => 3}}
val = h[:a][:b] rescue nil # => 3
val = h[:a][:c] rescue nil # => nil
val = h[:c][:b] rescue nil # => nil
关于ruby - 在哈希中访问哈希时如何处理潜在错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17512197/