基于排序值数组对哈希数组进行排序

时间:2015-02-08 09:09:25

标签: ruby-on-rails ruby arrays sorting hash

我有一系列哈希,如下所示:

user_quizzes = [{:id => 3897, :quiz_id => 1793, :user_id => 252}, {:id => 3897, :quiz_id => 1793, :user_id => 475}, {:id => 3897, :quiz_id => 1793, :user_id => 880}, {:id => 3897, :quiz_id => 1793, :user_id => 881}, {:id => 3897, :quiz_id => 1793, :user_id => 882}, {:id => 3897, :quiz_id => 1793, :user_id => 883}, {:id => 3897, :quiz_id => 1793, :user_id => 884}]

另外,根据特定条件,我采用了user_id' sorted_user_ids = [880, 881, 882, 883, 884, 475, 252] '来自相同哈希的密钥并对其进行排序,并在下面给出相同的数组:

user_quizzes

现在,我需要根据user_id数组中sorted_user_ids的顺序重新排列{{1}}。

任何人都可以帮助我。 :)

1 个答案:

答案 0 :(得分:3)

使用Enumerable#sort_byArray#sort_by!,您可以指定将用于比较的密钥:

user_quizzes = [
  {:id => 3897, :quiz_id => 1793, :user_id => 252},
  {:id => 3897, :quiz_id => 1793, :user_id => 475},
  {:id => 3897, :quiz_id => 1793, :user_id => 880},
  {:id => 3897, :quiz_id => 1793, :user_id => 881},
  {:id => 3897, :quiz_id => 1793, :user_id => 882},
  {:id => 3897, :quiz_id => 1793, :user_id => 883},
  {:id => 3897, :quiz_id => 1793, :user_id => 884}
]
sorted_user_ids = [880, 881, 882, 883, 884, 475, 252]
user_quizzes.sort_by { |x| sorted_user_ids.index(x[:user_id]) }
# => [{:id=>3897, :quiz_id=>1793, :user_id=>880},
#     {:id=>3897, :quiz_id=>1793, :user_id=>881},
#     {:id=>3897, :quiz_id=>1793, :user_id=>882},
#     {:id=>3897, :quiz_id=>1793, :user_id=>883},
#     {:id=>3897, :quiz_id=>1793, :user_id=>884},
#     {:id=>3897, :quiz_id=>1793, :user_id=>475},
#     {:id=>3897, :quiz_id=>1793, :user_id=>252}]

旁注:如果数组很大,sorted_user_ids.index(x[:user_id])可能成为瓶颈(重复O(n)操作)。

在这种情况下构建一个将user_id映射到订单的哈希:

sorted_user_ids = [880, 881, 882, 883, 884, 475, 252]
order = Hash[sorted_user_ids.each_with_index.to_a]
# => {880=>0, 881=>1, 882=>2, 883=>3, 884=>4, 475=>5, 252=>6}
user_quizzes.sort_by { |x| order[x[:user_id]] }
# => same as above.