根据项目数组对rails hash进行排序

时间:2011-03-30 19:00:05

标签: ruby-on-rails arrays hash

我有一个这样的数组:

['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} }

如果我需要在新问题中提出这个问题,请告诉我,我会这样做。

谢谢

2 个答案:

答案 0 :(得分: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) }

答案 1 :(得分:0)

在这种情况下,Array的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}}]
相关问题