2015-02-08 181 views
1

我有散列數組的數組散列數組如下給出:排序基於排序的值

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_idsorted_user_ids排列的順序重新排列。

任何人都可以請幫助我。 :)

回答

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. 
+0

在這種特定的情況下'user_quizzes.sort {| A,B | a [:user_id] <=> b [:user_id]}'更易讀易維護。雖然我理解執行時間的懲罰。 – mudasobwa 2015-02-08 09:13:08

+0

@mudasobwa,OP想按'sorted_user_ids'排序,而不是'user_id'本身:** ...根據'sorted_user_ids'數組中'user_id'的順序重新排列** – falsetru 2015-02-08 09:13:46

+0

噢,是的,你是對的,對不起。 – mudasobwa 2015-02-08 09:14:34