Ruby排序Hash By Inner Hash的计数值相同

时间:2021-09-28 15:42:22

I have a hash of hashes and what I'm trying to accomplish is to sort the hash based on the count of the inner hash's count of the same value. So let's say this is my hash.

我有哈希哈希,我想要完成的是根据相同值的内部哈希计数的数量对哈希进行排序。所以让我们说这是我的哈希。

hash = { 
         "Run1"=>{"March 24, 2013"=>"failed", "March 23, 2013"=>"failed", "March 21, 2013"=>"failed", "March 19, 2013"=>"passed", "March 18, 2013"=>"passed"},
         "Run2"=>{"March 24, 2013"=>"failed", "March 23, 2013"=>"failed", "March 21, 2013"=>"failed", "March 19, 2013"=>"failed", "March 18, 2013"=>"failed"} 
       }

I want to sort the hash so the Run2 appears before Run1 since I'm trying to sort by the number of times a run "failed"

我想对哈希进行排序,以便Run1出现在Run1之前,因为我试图按运行“失败”的次数排序

I'm thinking I need something like

我想我需要类似的东西

hash.sort_by{|key, innerHash| innerHash.values.count('failed')}

Any help or suggestions is greatly appreciated

非常感谢任何帮助或建议

1 个解决方案

#1


3  

A lil fix:

一个小修复:

hash.sort_by { |_,h| -h.values.count('failed') } # notice force negative

...and should work. Take in mind sort_by always returns an array, so maybe you'd want to:

......并且应该工作。请记住sort_by总是返回一个数组,所以也许你想要:

sorted_hash = Hash[hash.sort_by { |_,h| -h.values.count('failed') }]

#1


3  

A lil fix:

一个小修复:

hash.sort_by { |_,h| -h.values.count('failed') } # notice force negative

...and should work. Take in mind sort_by always returns an array, so maybe you'd want to:

......并且应该工作。请记住sort_by总是返回一个数组,所以也许你想要:

sorted_hash = Hash[hash.sort_by { |_,h| -h.values.count('failed') }]