From: "David A. Black" Date: 2009-06-20T21:28:28+09:00 Subject: Re: need a hash/iteration tutorial...text reading. --1926193751-1290970970-1245500894=:9157 Content-Type: MULTIPART/MIXED; BOUNDARY="1926193751-1290970970-1245500894=:9157" This message is in MIME format. The first part should be readable text, while the remaining parts are likely unreadable without MIME-aware tools. --1926193751-1290970970-1245500894=:9157 Content-Type: TEXT/PLAIN; charset=windows-1252; format=flowed Content-Transfer-Encoding: 8BIT Hi -- On Sat, 20 Jun 2009, Robert Dober wrote: > 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. You'd want to throw in a flatten(1) to unwrap the inner arrays: [*hash.sort_by {...}.flatten(1)] 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 --1926193751-1290970970-1245500894=:9157-- --1926193751-1290970970-1245500894=:9157--