如何在Ruby中迭代Hash

时间:2011-07-01 22:37:26

标签: ruby xml hash loops

我正在处理像这样的xml:

<fare_master_pricer_reply>  
 <flight_index>

  <group_of_flights>
    <flight_details>
    </flight_details>
    .
    .
    <flight_details>
    </flight_details>   
   </group_of_flights>

  <group_of_flights>
    <flight_details>
    </flight_details>
    .
    .
    <flight_details>
    </flight_details>   
   </group_of_flights>
     .    
     .   
   <group_of_flights>
    <flight_details>
    </flight_details>
    .
    .
    <flight_details>
    </flight_details>   
   </group_of_flights>  
  </flight_index> 
 </fare_master_pricer_reply>

这是在哈希对象中给出的。我需要遍历那个哈希,到目前为止我已经编码了这个:

@flights = response.to_hash[:fare_master_pricer_calendar_reply][:flight_index]
while (@flight_groups = @flights[:group_of_flights]) != nil
  while (@flight = @flight_groups[:flight_details])
    @time_data = @flight[:flight_information][:product_date_time]
    @html = "<tr>"
    @html += "<td>" + @time_data[:date_of_departure] + "</td>"
    @html += "<td>" + @time_data[:date_of_arrival] + "</td>"
    @html += "<td>" + @flight[:location][:location_id] + "</td>"
    @html += "</tr>"
  end
  @html = "<tr><td>**</td><td>**</td><td>**</td><td>**</td><td>**</td><td>**</td><td>**</td></td>"
end

但我得到

  

TypeError(符号作为数组索引):

在这一行:

while (@flight = @flight_groups[:flight_details])

为什么我的哈希变成一个数组?这是迭代原始哈希的正确方法吗?

谢谢!!!

2 个答案:

答案 0 :(得分:10)

迭代哈希的正确方法就是这样

@flights.each do |key, value|
end

请参阅Hash#each

答案 1 :(得分:3)

查看您的XML:

<fare_master_pricer_reply>  
 <flight_index>
  <group_of_flights>
   <!--...-->
  </group_of_flights>
  <group_of_flights>
   <!--...-->
  </group_of_flights>
  <group_of_flights>
   <!--...-->
  </group_of_flights>
  <!--...-->

因此<flight_index>包含<group_of_flights>个元素的列表。这自然会表示为数组,而不是哈希。

然后,你这样做:

@flights = response.to_hash[:fare_master_pricer_calendar_reply][:flight_index]

这等同于:

h = response.to_hash
@flights = [:fare_master_pricer_calendar_reply][:flight_index]

因此@flights最终会得到<flight_index>的内容。如上所述,<flight_index>只是<group_of_flights>元素列表的容器,您的XML mangler可能将该列表转换为列表的最自然表示,这将为您提供Array的实例而不是哈希。

您不希望将@flights作为哈希进行迭代,而是将其作为数组进行迭代。您可能会遇到内部<flight_details>元素的相同情况。

相关问题