遍历嵌套哈希/数组

时间:2020-07-30 21:03:18

标签: ruby

我从api调用获得以下响应代码。我正在尝试将以下数据提取到我的数据库中:

Duration ("5 Hours and 21 Minutes"),
Departure ("From LAX at 2020/10/05 - 16:00),
Arrival ("Arriving in JFK at 2020/10/06 - 21:00"),
Price ("256.46"),
Stops ("0")
Currency ("Euro")
Cabin ("Economy")

我的以下代码获得了一些属性,但就我所知,我发现它变得很难编码和丑陋,并且想知道如何使它变得更好:

  res.data.select do |t|
    puts "Flight's total price:#{t["price"]["currency"]}#{t["price"]["total"]}"  
    t["itineraries"].select do |new_t|  
      puts "Flight's duration is: #{new_t["duration"]}"    
      new_t["segments"].select do |another_t|
        puts "Departue at: #{another_t["departure"]["at"]} from #{another_t["departure"]["iataCode"]}"
        puts "Arriving at: #{another_t["arrival"]["at"]} from #{another_t["arrival"]["iataCode"]}"
      end  
    end  
  end 

以下是变量中保存的api的响应代码

    {"type"=>"flight-offer",
 "id"=>"1",
 "source"=>"GDS",
 "instantTicketingRequired"=>false,
 "nonHomogeneous"=>false,
 "oneWay"=>false,
 "lastTicketingDate"=>"2020-07-31",
 "numberOfBookableSeats"=>9,
 "itineraries"=>
  [{"duration"=>"PT5H56M",
    "segments"=>
     [{"departure"=>
        {"iataCode"=>"JFK", "terminal"=>"4", "at"=>"2020-10-01T09:45:00"},
       "arrival"=>
        {"iataCode"=>"LAX", "terminal"=>"2", "at"=>"2020-10-01T12:41:00"},
       "carrierCode"=>"DL",
       "number"=>"653",
       "aircraft"=>{"code"=>"76W"},
       "operating"=>{"carrierCode"=>"DL"},
       "duration"=>"PT5H56M",
       "id"=>"30",
       "numberOfStops"=>0,
       "blacklistedInEU"=>false}]},
   {"duration"=>"PT5H21M",
    "segments"=>
     [{"departure"=>
        {"iataCode"=>"LAX", "terminal"=>"2", "at"=>"2020-10-05T16:00:00"},
       "arrival"=>
        {"iataCode"=>"JFK", "terminal"=>"4", "at"=>"2020-10-06T00:21:00"},
       "carrierCode"=>"DL",
       "number"=>"682",
       "aircraft"=>{"code"=>"76W"},
       "operating"=>{"carrierCode"=>"DL"},
       "duration"=>"PT5H21M",
       "id"=>"41",
       "numberOfStops"=>0,
       "blacklistedInEU"=>false}]}],
 "price"=>
  {"currency"=>"EUR",
   "total"=>"256.46",
   "base"=>"239.00",
   "fees"=>
    [{"amount"=>"0.00", "type"=>"SUPPLIER"},
     {"amount"=>"0.00", "type"=>"TICKETING"}],
   "grandTotal"=>"256.46"},
 "pricingOptions"=>
  {"fareType"=>["PUBLISHED"], "includedCheckedBagsOnly"=>false},
 "validatingAirlineCodes"=>["DL"],
 "travelerPricings"=>
  [{"travelerId"=>"1",
    "fareOption"=>"STANDARD",
    "travelerType"=>"ADULT",
    "price"=>{"currency"=>"EUR", "total"=>"256.46", "base"=>"239.00"},
    "fareDetailsBySegment"=>
     [{"segmentId"=>"30",
       "cabin"=>"ECONOMY",
       "fareBasis"=>"VAVQA0BC",
       "brandedFare"=>"BASICECON",
       "class"=>"E",
       "includedCheckedBags"=>{"quantity"=>0}},
      {"segmentId"=>"41",
       "cabin"=>"ECONOMY",
       "fareBasis"=>"VAVQA0BC",
       "brandedFare"=>"BASICECON",
       "class"=>"E",
       "includedCheckedBags"=>{"quantity"=>0}}]}]}

感谢您阅读并尝试提供帮助。我希望您安全,并祝您有美好的一天。

0 个答案:

没有答案
相关问题