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

Arrays 如何根据其中一个列表的顺序对两个列表进行排序?,arrays,ruby,sorting,Arrays,Ruby,Sorting,我有两个哈希数组,按:id排序: 我把它们合并在一起得到结果。我想按:id: 你能帮我做到吗?如果我这样做: 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, :

我有两个哈希数组,按:id排序:

我把它们合并在一起得到结果。我想按:id:

你能帮我做到吗?如果我这样做:

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"}]

但我想要其他结果——根据事件id的顺序:你这是什么意思?@YanisVieilly我想要在其他数组中无损插入排序数组。它应该按foo字段排序,而不会丢失以前按id排序的顺序4,5我仍然不太确定您到底想做什么,但是如果您想按id按多个值排序,那么按foo可以执行以下操作:all.sort\u by!{| ob |[ob[:id],ob[:foo]]}@YanisVieilly如果我喜欢的话-它将按id排序,因为id是唯一的值,所以它将排序而不使用foo字段,结果将是另一个,tryhash是随机访问结构,排序没有任何用处。你为什么要分类一个?为什么你不能提取密钥并对其进行排序?
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"}]
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