简体   繁体   English

在Ruby / Rails中处理多级哈希

[英]Dealing with Multi-Level Hashes in Ruby/Rails

I'm requesting data from an API that returns a multi-level hash in a rails app. 我正在从API中请求数据,该API在Rails应用程序中返回多级哈希。 I need to access information at different points in the API response, so I have code like this in my view: 我需要在API响应的不同位置访问信息,因此在我的视图中有如下代码:

<%= @api_response["Hash 1"]["Hash 2"]["Hash 3"]["value"] %>

In the same view file I might have something like: 在同一个视图文件中,我可能会有类似的内容:

<%= @api_response["Hash 1"]["value"] %>

Is this an acceptable way to deal with an large hash from an API response? 这是处理来自API响应的大哈希值的可接受方法吗? Or is there a better way this could be handled? 还是有更好的方法可以处理?

您可以看一下递归开放结构gem ,它允许像方法一样访问哈希,而且也更清洁。

Since Ruby 2.3.0, Ruby now natively supports this with Hash#dig . 从Ruby 2.3.0开始,Ruby现在通过Hash#dig支持此功能。 From the documentation: 从文档中:

h = { foo: {bar: {baz: 1}}}

h.dig(:foo, :bar, :baz)           #=> 1
h.dig(:foo, :zot, :xyz)           #=> nil

g = { foo: [10, 11, 12] }
g.dig(:foo, 1)                    #=> 11

Another, more convenient example usage: 另一个更方便的示例用法:

hpath = %i[foo bar baz]
h.dig(*hpath)                     #=> 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM