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.
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With