如何根据其中一个顺序对两个列表进行排序?

时间:2015-08-23 23:40:49

标签: arrays ruby sorting

我有两个按: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"}]

1 个答案:

答案 0 :(得分: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