开发者

How to iterate over a Hash in Ruby

开发者 https://www.devze.com 2023-03-17 06:11 出处:网络
I\'m dealing with an xml like this: <fare_master_pricer_reply> <flight_index> <group_of_flights>

I'm dealing with an xml like this:

<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>

That is given to me in a hash object. I need to iterate over that hash and so far I've coded this:

@flights = response.t开发者_如何学JAVAo_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

but I get

TypeError (Symbol as array index):

in this line:

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

Why my hash is becoming an array? Is this the right way to iterate over my original hash?

Thank you!!!


The correct way to iterate over a hash is like so

@flights.each do |key, value|
end

See Hash#each


Have a look at your 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>
  <!--...-->

So <flight_index> contains a list of <group_of_flights> elements. That would naturally be represented as an array, not a hash.

Then, you do this:

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

And that is equivalent to this:

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

So @flights ends up with the contents of <flight_index>. As noted above, <flight_index> is just a container for a list of <group_of_flights> elements and your XML mangler is probably converting that list to the most natural representation of a list, that would give you an instance of Array rather than a Hash.

You don't want to iterate over @flights as a Hash, iterate over it as an Array instead. You'll probably face the same situation with the inner <flight_details> elements.

0

精彩评论

暂无评论...
验证码 换一张
取 消