小编Far*_*ooq的帖子

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

我通过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)

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

ruby

1
推荐指数
1
解决办法
52
查看次数

标签 统计

ruby ×1