我有一个像这样的数组:
['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
(以及将 :total 转换为字符串的 .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) }
关于ruby-on-rails - 根据项目数组对 Rails 哈希进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5490892/