Ruby on rails 基于项目数组对rails哈希进行排序

Ruby on rails 基于项目数组对rails哈希进行排序,ruby-on-rails,arrays,hash,Ruby On Rails,Arrays,Hash,我有这样一个数组: ['one','three','two','four'] [{'three' => {..some data here..} }, {'two' => {..some data here..} }, {:total => some_total }] # etc... {'one' => {:total => 1, :some_other_value => 5}, 'two' => {:total => 2, :some_ot

我有这样一个数组:

['one','three','two','four']
[{'three' => {..some data here..} }, {'two' => {..some data here..} }, {:total => some_total }] # etc...
{'one' => {:total => 1, :some_other_value => 5}, 'two' => {:total => 2, :some_other_value => 3} }
我有一个如下的散列数组:

['one','three','two','four']
[{'three' => {..some data here..} }, {'two' => {..some data here..} }, {:total => some_total }] # etc...
{'one' => {:total => 1, :some_other_value => 5}, 'two' => {:total => 2, :some_other_value => 3} }
我想按第一个数组对哈希数组进行排序。我知道我能做到:

array_of_hashes.sort_by{|k,v| k.to_s} to sort them and it will sort by the key 
(以及要转换为字符串的.to_s:total)

我怎样才能做到这一点

编辑:

我对设置的方式不正确,实际上是这样的:

['one','three','two','four']
[{'three' => {..some data here..} }, {'two' => {..some data here..} }, {:total => some_total }] # etc...
{'one' => {:total => 1, :some_other_value => 5}, 'two' => {:total => 2, :some_other_value => 3} }
如果我需要提出一个新的问题,只要让我知道,我会这样做


谢谢

在这种情况下,数组的
索引
方法是您的朋友:

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

与ctcherry答案类似,但使用排序方式

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) }

您使用的是什么Ruby版本?我得到了这个,并对您的解决方案进行了修改:。sort_by{k,v|k='z',除非sort_list.include?(k);sort_list.index(k)}。我肯定有更好的办法,但我不知道。此外,我在排序栏中添加了“z”,以便为它提供一个未找到的位置。