如何在访问哈希内部的哈希时处理潜在的错误?

dsp*_*099 3 ruby hash

有时在处理API响应时,我最终会写一些类似于:

what_i_need = response["key"]["another key"]["another key 2"]
Run Code Online (Sandbox Code Playgroud)

问题是,如果"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
Run Code Online (Sandbox Code Playgroud)

我还考虑过猴子修补NilClass你尝试访问nil["something"]它会返回nil,但我不确定这是否是最好的方式来解决它,如果它甚至可能.

Aru*_*hit 9

使用带有默认值的Hash #fetch.

h = {:a => 2}
h.fetch(:b,"not present")
# => "not present"
h.fetch(:a,"not present")
# => 2
Run Code Online (Sandbox Code Playgroud)

如果没有默认值,它将抛出KeyError.

h = {:a => 2}
h.fetch(:b)
# ~> -:2:in `fetch': key not found: :b (KeyError)
Run Code Online (Sandbox Code Playgroud)

但是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
Run Code Online (Sandbox Code Playgroud)


saw*_*awa 6

Ruby 2.0有NilClass#to_h.

what_i_need = response["key"].to_h["another key"].to_h["another key 2"]
Run Code Online (Sandbox Code Playgroud)