Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"]
like image 962
San Backups Avatar asked Sep 14 '26 09:09

San Backups


2 Answers

Here's a one-liner for you (I love ruby!):

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

Hope that helps!

like image 90
Xavier Holt Avatar answered Sep 16 '26 04:09

Xavier Holt


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]]
like image 28
Shamith c Avatar answered Sep 16 '26 05:09

Shamith c



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!