我有散列的阵列如下面给出:
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
阵列。
任何人都可以请帮我在这。 :)
使用Enumerable#sort_by
或Array#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
s到在这种情况下命令:
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.