From: "David A. Black" Date: 2009-06-19T22:09:16+09:00 Subject: Re: need a hash/iteration tutorial...text reading. 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). 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