Tob*_*ner 2 arrays hash ruby-on-rails
我有这样一个数组:
['one','three','two','four']
Run Code Online (Sandbox Code Playgroud)
我有一个像这样的哈希数组:
[{'three' => {..some data here..} }, {'two' => {..some data here..} }, {:total => some_total }] # etc...
Run Code Online (Sandbox Code Playgroud)
我想通过第一个数组对哈希数组进行排序.我知道我能做到:
array_of_hashes.sort_by{|k,v| k.to_s} to sort them and it will sort by the key
Run Code Online (Sandbox Code Playgroud)
(以及要转换的.to_s:总计为字符串)
我怎样才能做到这一点?
编辑:
关于如何设置我是不正确的,它实际上是这样的:
{'one' => {:total => 1, :some_other_value => 5}, 'two' => {:total => 2, :some_other_value => 3} }
Run Code Online (Sandbox Code Playgroud)
如果我需要在新问题中提出这个问题,请告诉我,我会这样做.
谢谢
类似于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) }
Run Code Online (Sandbox Code Playgroud)