开发者

How do I fix this hash and/or array sorting in Rails?

开发者 https://www.devze.com 2023-02-01 18:54 出处:网络
I\' writing a piece of code that will integrate with TripIt.In my TripIt plans, I have an example trip with ONE item (Activity).I want to sort by date.The sort fails.When I add another Activity the so

I' writing a piece of code that will integrate with TripIt. In my TripIt plans, I have an example trip with ONE item (Activity). I want to sort by date. The sort fails. When I add another Activity the sort works. I believe it's because of when it's a single item, it's a hash and when it's a collection of items, it's an array of hashes.

Here is my sort method:

  @tripit_trip[k].sort_by { |h| h["StartDateTime"]["date"] }.each do |o|
    o["ObjectType"] = "ActivityObject"
    tmp[ o["StartDateTime"]["date"] ] = [] if tmp[ o["StartDateTime"]["date"] ].nil?
    tmp[ o["StartDateTime"]["date"] ] << o
  end

It fails on the first line.

Here is what the data looks like coming from TripIt:

 // One item
 --- 
 id: "20392856"
 trip_id: "11086745"
 is_client_traveler: "true"
 relative_url: /reservation/show/id/20392856
 display_name: Programming
 is_purchased: "true"
 StartDateTime: 
   date: "2011-01-09"
   timezone: Asia/Ulaanbaatar

This is the TripIt data when there are two items:

 // 开发者_开发知识库Two items

    --- 
    - id: "20631958"
      trip_id: "11086745"
      is_client_traveler: "true"
      relative_url: /reservation/show/id/20631958
      display_name: Programming 2
      is_purchased: "true"
      StartDateTime: 
        date: "2011-01-09"
        timezone: Asia/Ulaanbaatar
    - id: "20392856"
      trip_id: "11086745"
      is_client_traveler: "true"
      relative_url: /reservation/show/id/20392856
      display_name: Programming
      is_purchased: "true"
      StartDateTime: 
        date: "2011-01-09"
        timezone: Asia/Ulaanbaatar

Any insight on what I'm doing wrong would be wonderful.

Thanks!


With a single item in the list, you don't exactly need to sort. Why not just put an if in the code that skips the sort if there's only one returned item?

0

精彩评论

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

关注公众号