2011-03-30 30 views
2

我有一個這樣的數組:排序軌哈希基於項目的陣列

['one','three','two','four'] 

我有哈希像這樣的數組:

[{'three' => {..some data here..} }, {'two' => {..some data here..} }, {:total => some_total }] # etc... 

我想通過哈希值的數組排序第一個數組。我知道我可以做:

array_of_hashes.sort_by{|k,v| k.to_s} to sort them and it will sort by the key 

(和.to_s轉換:總爲字符串)

我怎樣才能做到這一點?

編輯:

我是不正確的關於這是怎麼設置的,它實際上是這樣的:

{'one' => {:total => 1, :some_other_value => 5}, 'two' => {:total => 2, :some_other_value => 3} } 

如果我需要把這個新的問題,只是讓我知道,我會去做。

謝謝

+0

你用什麼Ruby版本? – fl00r 2011-03-30 19:49:52

回答

6

類似ctcherry回答,但使用sort_by。

sort_arr = ['one','three','two','four'] 
hash_arr = [{'three' => {..some data here..} }, {'two' => {..some data here..} }] 

hash_arr.sort_by { |h| sort_arr.index(h.keys.first) } 
+0

我得到這個與您的解決方案一起修改:.sort_by {| k,v | k ='z'除非sort_list.include?(k); sort_list.index(K)}。我相信有更好的辦法,但我不知道。我還向sort_arr添加了'z',爲它提供了一個沒有找到的地方。 – 2011-03-31 14:18:24

0

陣列的index方法是你在這種情況下的朋友:

sort_list = ['one','three','two','four'] 

data_list = [{'three' => { :test => 3 } }, {'two' => { :test => 2 } }, {'one' => { :test => 1 } }, {'four' => { :test => 4 } }] 

puts data_list.sort { |a,b| 
sort_list.index(a.keys.first) <=> sort_list.index(b.keys.first) 
}.inspect 

,導致,順序相同的源陣列:

[{"one"=>{:test=>1}}, {"three"=>{:test=>3}}, {"two"=>{:test=>2}}, {"four"=>{:test=>4}}]