简体   繁体   English

Ruby Hash - 按值和打印键排序

[英]Ruby Hash - sort by value and print keys

This is my hash. 这是我的哈希。

=> {"f11"=>1, "f12"=>3, "f13"=>3, "f07"=>5, "f10"=>1}

I'd like to sort by the values largest to smallest and then make an array out of the keys. 我想按从最大到最小的值排序,然后从键中创建一个数组。

=> ["f07", "f12", "f13", "f11", "f10"]

Here's a one-liner for you (I love ruby!): 这是给你的单行(我爱红宝石!):

h.keys.sort {|a, b| h[b] <=> h[a]}

Hope that helps! 希望有所帮助!

Hash has the Enumerable module mixed in which provides us with methods like sort and sort_by.In this situation we can use sort_by to get a collection by order of values. Hash混合了Enumerable模块,它为我们提供了sort和sort_by等方法。在这种情况下,我们可以使用sort_by按值的顺序获取集合。

 h={"f11"=>1, "f12"=>3, "f13"=>3, "f07"=>5, "f10"=>1} 
 h.sort_by{ |key, value| -value }  
 => [["f07", 5], ["f12", 3], ["f13", 3], ["f11", 1], ["f10", 1]]

更短!:

h.keys.sort_by{|a| h[a]}.reverse
a = {"f11"=>1, "f12"=>3, "f13"=>3, "f07"=>5, "f10"=>1}
b = Hash[a.sort_by{|k,v| v}]
puts b.keys.reverse

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

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