From: Tomasz Wegrzanowski Date: 2002-01-06T10:50:37+09:00 Subject: [ruby-talk:30321] Re: Sorting a Hash by value of integer stored in the Hash On Sun, Jan 06, 2002 at 10:34:57AM +0900, Michael Joner wrote: > I have a program which creates a Hash array. The ultimate result is a > word as the key and an integer as the value. I'd like to sort by the > value in the Hash, then print the ten highest values and their associated > keys. I understand that there is a sort Method but I'm not sure how to > get it to work on a Hash. I know that if my data were simply stored in an > array I could use: > > myArray.sort { |a,b| b <=> a } > > So I've tried the same technique on the Hash: > > myHash.sort { |a,b| b <=> a } > > Printing the first ten elements of the resulting object (which was an > array) returned words starting with z and then y (in reverse alphabetical) > and the associated value, run together. This isn't what I'm trying to > get. The sort apparently was performed on the keys, but I want to do sort > on the values. Is there a way to do this? If there aren't any duplicated elements, it's easiest to just invert the hash: hash_new = hash.invert ... and operate on inverted hash. If there are, it's probably easiest to make hash of arrays: new_hash=Hash.new([]) hash.each_pair { |k,v| new_hash[v].push k } ...