Rails 遍历深哈希数组 [英] Rails traverse deep array of hashes

查看:50
本文介绍了Rails 遍历深哈希数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到了这个非常令人困惑的哈希数组作为 API 响应.

I got this very confusing array of hashes as an API response.

http://jsfiddle.net/PP9N5/

(完整的响应是大量的.只发布其中的一部分,但它涵盖了响应的所有元素)我怎样才能到达航空公司".

( the full response is massive. Posting only a part of it but it covers all elements of the response) How can I get to "airlines".

我试过了

<% @flight["air_search_result"]["onward_solutions"]["solution"].each do|h| %>
  <strong><%=h["pricing_summary"]["total_fare"] %></strong> - 
  <% h["flights"]["flight"]["segments"]["segment"].each do |s| %>
    <%= s['airline'] %>
  <% end %> <br> <hr>
<% end %>

我收到这个错误

无法将字符串转换为整数

can't convert String into Integer

我做了一些修改,比如

<%= h["flights"]["flight"]["segments"]["segment"].first["airline"] %>
Error received - can't convert String into Integer

<%= h["flights"]["flight"]["segments"]["segment"][0]["airline"] %>
Error received - undefined method '[]' for nil:NilClass

有没有一种简单的方法,就像我说的那样找到一个键航空公司",并为该键返回其值.我偶然发现了这个链接,虽然我没有得到任何错误,我也没有得到任何结果.

Isnt there a simple way, like I say to find a key "airline" and for that key it returns its value. I stumbled upon this link, though I dont get any error, I also dont get any result.

谢谢.

更新

我做到了

<% h["flights"]["flight"]["segments"]["segment"].each do |o,p| %>
<% if o=="airline" %> <%= p %> <% end %>
 <% end %> <br> <hr>
<% end %>

在段内没有数组的情况下,我可以获得很少的航空公司值.
例如,我可以得到离开日期时间是 2014-07-07T07:10:00 的位置,索引 = 5.

I can get few values of airlines where inside segment there is no array.
For eg, i can get where departure_date_time is 2014-07-07T07:10:00, index = 5.

http://jsfiddle.net/PP9N5/1/(向下滚动)

推荐答案

这里是一些您可以添加的代码,它们将提取与 Hash 中的任何 Hash 中的参数相等的所有键代码>:

Here is some code you can add which will extract all keys equal the parameter in any Hash within your Hash:

class Hash
  def deep_find(query, &block)
    flat_map do |key, value|
      if key == query
        yield value if block_given?
        [value]
      elsif value.is_a? Hash
        value.deep_find(query, &block)
      elsif value.is_a? Array
        value.select { |i| i.is_a? Hash }.flat_map { |h| h.deep_find(query, &block) }
      end
    end
  end
end

示例:

hash = {"h" => [{ 'x' => [1, 5] }, { 'x' => 2 }, { 'f' => { 'x' => [3, 4] } }], 'x' => 6 }
hash.deep_find('x') { |x| puts "#{x}" }
# [1, 5]
# 2
# [3, 4]
# 6
# => [[1, 5], 2, [3, 4], 6]

这篇关于Rails 遍历深哈希数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆