From: Robert Dober Date: 2009-06-20T21:15:23+09:00 Subject: Re: need a hash/iteration tutorial...text reading. On Fri, Jun 19, 2009 at 3:09 PM, David A. Black wrote: > Hi -- > > On Fri, 19 Jun 2009, Matt Neuburg wrote: > >> Steven Demonnin wrote: >> >>> What I want to know is, is it possible to create a has where the key is >>> the word, and the value is the number of occurrences of the word in the >>> text, and then sort the hash by the values? >> >> That is called a "histogram" and is one of the most common examples >> (Google is your friend). The sticking point here is what you mean by a >> "word". If you're willing to accept a fairly crude definition of this >> notion, then that is an example I develop in the Blocks section of my >> Ruby tutorial chapter here: >> >> http://www.apeth.com/ruby/02justenoughruby.html >> >> To sort, add this line: >> >> wds = h.sort {|x,y| x[1] <=> y[1]} > > Or, slightly more compact: > >  wds = h.sort_by {|x| x[1] } > >> Note that the concept "sort a hash" has no real meaning, since a hash is >> not ordered. What you can do is to convert to an array and sort the >> array. > > In 1.9 hashes are ordered, but by key-insertion order. You can't > change the order, so you can't sort back into a hash (unless you > create a new hash manually using the sorted order). IIRC the insertion order is maintained correctly for literals and Hash[] thus Hash[ * a_hash.sort_by{ whatever } ] should do the trick. Cheers Robert > > > David > > -- > David A. Black / Ruby Power and Light, LLC > Ruby/Rails consulting & training: http://www.rubypal.com > Now available: The Well-Grounded Rubyist (http://manning.com/black2) > "Ruby 1.9: What You Need To Know" Envycasts with David A. Black > http://www.envycasts.com > > -- Toutes les grandes personnes ont d’abord été des enfants, mais peu d’entre elles s’en souviennent. All adults have been children first, but not many remember. [Antoine de Saint-Exupéry]