如何在单个语句/检查中替换嵌套哈希的多个nil检查?

Far*_*ooq 1 ruby

我通过API调用获得响应,我感兴趣的值是:

JSON.parse(response).first['property/details']['result']['assessment']

JSON.parse(response) 给出一个数组,我选择第一个哈希元素并遍历其中的嵌套哈希值以获得所需的值.

问题是,任何会破坏代码的值都可以为零,因此我必须执行以下操作:

if property=JSON.parse(response).first
     if property['property/details']
         if result=property['property/details']['result']
             # get the value result['assessment']
         end
     end
end
Run Code Online (Sandbox Code Playgroud)

这看起来非常麻烦,我想用尽可能少的线来做,最好是一条线.

Ste*_*fan 5

dig 是你的朋友:

JSON.parse(response).dig(0, 'property/details', 'result', 'assessment')
Run Code Online (Sandbox Code Playgroud)

您可以传递索引和键,以遍历嵌套的数组/哈希结构.