繁体   English   中英

根据项目数组对Rails哈希排序

[英]Sort rails hash based on array of items

我有一个像这样的数组:

['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转换成字符串的.to_s)

我怎样才能做到这一点?

编辑:

我不知道该如何设置,实际上是这样的:

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

如果我需要提出一个新问题,请告诉我,我会做的。

谢谢

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

在这种情况下,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}}]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM