2013-01-03 67 views
0

我有一個數組像這種哈希:如何紅寶石根據一些自定義規則

["Is", "Gandalf", "The", "Gray", "Insane"] 

,我想根據數組中的關鍵位置進行排序的哈希值。例如,我想排序:

{:count=>21, "Is"=>19, "Gandalf"=>1, "Gray"=>0, "Insane"=>1, "The"=>5} 

成這樣:

{"Is"=>19, "Gandalf"=>1, "The"=>5, "Gray"=>0, "Insane"=>1, :count=>21} 

另一個例子是排序如下:

{:count=>3, "Is"=>11, "Insane"=>22, "Gray"=>0, "Gandalf"=>12, "The"=>2} 

成這樣:

{"Is"=>11, "Gandalf"=>12, "The"=>2, "Gray"=>12, "Insane"=>22, :count=>3} 

如何做到這一點?

+2

你爲什麼要對散列進行排序?哈希是隨機訪問的數據結構,因此對鍵進行排序純粹是美觀的,絕對沒有價值或訪問速度的提高。換句話說,這是浪費時間。 –

+0

我沒有看性能改進,我正在循環通過前端的散列,並對每個條目進行操作(條目是來自問題的散列)。我需要它每次都以相同的順序顯示 –

+0

解釋前端發生的情況。因爲您的請求具有代碼異味,並且如果您要將數據發送到Web前端,請使用JSON對數據進行編碼,將其發送到瀏覽器,讓JavaScript將JSON解碼爲散列,然後訪問所得到的散列值就像正常一樣。 –

回答

2
class Hash 
    def sort_by_array a; Hash[sort_by{|k, _| a.index(k) || length}] end 
end 

將第例如工作:

a = ["Is", "Gandalf", "The", "Gray", "Insane"] 

{:count=>21, "Is"=>19, "Gandalf"=>1, "Gray"=>0, "Insane"=>1, "The"=>5}.sort_by_array(a) 
# => {"Is"=>19, "Gandalf"=>1, "The"=>5, "Gray"=>0, "Insane"=>1, :count=>21} 

但是,它不會與工作你的第二個例子,因爲你的結果xpect爲第二個不只是排序,也需要對"Gray"改變值:

{:count=>3, "Is"=>11, "Insane"=>22, "Gray"=>0, "Gandalf"=>12, "The"=>2}.sort_by_array(a) 
# => {"Is"=>11, "Gandalf"=>12, "The"=>2, "Gray"=>0, "Insane"=>22, :count=>3} 

# You wanted 
# => {"Is"=>11, "Gandalf"=>12, "The"=>2, "Gray"=>12, "Insane"=>22, :count=>3} 

既然是不清楚的地方爲"Gray"12從何而來,你的問題不能的方式,滿足回答你的第二個例子。