2015-08-23 85 views
-3

我有:id排序散列值的兩個數組:如何根據其中之一的順序對兩個列表進行排序?

tweets = [{ id: 1, foo: 3, type: 'tweet' }, 
      { id: 2, foo: 5, type: 'tweet' }, 
      { id: 3, foo: 9, type: 'tweet' }] 

events = [{ id: 4, foo: 6, type: 'event' }, 
      { id: 5, foo: 1, type: 'event' }] 

我合併他們得到的結果哈希all。我想按:id的順序排序:

[{:id=>1, :foo=>3, :type=>"tweet"}, 
    {:id=>2, :foo=>5, :type=>"tweet"}, 
    {:id=>4, :foo=>6, :type=>"event"}, 
    {:id=>5, :foo=>1, :type=>"event"}, 
    {:id=>3, :foo=>9, :type=>"tweet"}] 

你能幫我實現嗎?如果我做的:

all.sort_by! { |ob| ob[:foo] } 

我收到:

[{:id=>5, :foo=>1, :type=>"event"}, 
    {:id=>1, :foo=>3, :type=>"tweet"}, 
    {:id=>2, :foo=>5, :type=>"tweet"}, 
    {:id=>4, :foo=>6, :type=>"event"}, 
    {:id=>3, :foo=>9, :type=>"tweet"}] 
+0

_but我希望其他的結果 - 根據events_的編號順序: 你這是什麼意思? –

+0

@YanisVieilly我想在其他數組中進行無損插入排序數組。它應該按'foo'字段進行排序而不會丟失以前的訂單** id **(4,5) –

+0

我仍然不確定您想要完全做什麼,但是如果您想按多個值排序(在您的通過'id',然後通過'foo'),你可以執行以下操作:'all.sort_by! {| ob | [ob [:id],ob [:foo]]}' –

回答

0
class Array 
    def reverse_each_with_index(&block) 
    (0...length).reverse_each do |i| 
     block.call self[i], i 
    end 
    end 
end 

def sort_by_foo(events:, tweets:) 
    result = events.clone 
    tweets.reverse_each do |twt| 
    inserted = false 
    result.reverse_each_with_index do |evn, i| 
     if twt[:foo] <= evn[:foo] && evn[:type] == 'event' 
     result.insert(i + 1, twt) 
     inserted = true 
     break 
     end 
    end 
    result.unshift(twt) unless inserted 
    end 
    result 
end 
相關問題