Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!aioe.org!news.stack.nl!talisker.lacave.net!lacave.net!not-for-mail From: jake kaiden Newsgroups: comp.lang.ruby Subject: Re: hash of arrays Date: Tue, 12 Apr 2011 22:05:01 -0500 Organization: Service de news de lacave.net Lines: 67 Message-ID: <0f5f3ec73bfb62bbcb3e566d55e16e48@ruby-forum.com> References: <17ed4aba89dcdda100deb6592ec4f9f5@ruby-forum.com> NNTP-Posting-Host: bristol.highgroove.com Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 7bit X-Trace: talisker.lacave.net 1302663925 11652 65.111.164.187 (13 Apr 2011 03:05:25 GMT) X-Complaints-To: abuse@lacave.net NNTP-Posting-Date: Wed, 13 Apr 2011 03:05:25 +0000 (UTC) In-Reply-To: <17ed4aba89dcdda100deb6592ec4f9f5@ruby-forum.com> X-Received-From: This message has been automatically forwarded from the ruby-talk mailing list by a gateway at comp.lang.ruby. If it is SPAM, it did not originate at comp.lang.ruby. Please report the original sender, and not us. Thanks! For more details about this gateway, please visit: http://blog.grayproductions.net/categories/the_gateway X-Mail-Count: 381394 X-Ml-Name: ruby-talk X-Rubymirror: Yes X-Ruby-Talk: <0f5f3ec73bfb62bbcb3e566d55e16e48@ruby-forum.com> Xref: x330-a1.tempe.blueboxinc.net comp.lang.ruby:2725 David Sprague wrote in post #992397: > I'm wrote this code to bin a list of words by word-length: hi david, if you're just trying to group words by their length, i'm not sure why you need a hash of arrays, a simple hash would do... list = %W[a cd def ghi jklm] hash = {} list.collect{|entry| hash[entry.length] = entry} p hash => {1=>"a", 2=>"cd", 3=>"ghi", 4=>"jklm"} the problem here is that any words of the same length would result in only one key (the last one) having the value of the word. you could just switch, and use the word as the key, and the length as the value... list.collect{|entry| hash[entry] = entry.length} => {"cd"=>2, "a"=>1, "jklm"=>4, "def"=>3, "ghi"=>3} but of course if you repeat words, you'll have the same problem. the quickest (and probably dumbest) solution i can think of is adding some kind of "unique id" to each key, so that they don't get lost - list = %W[a cd def ghi jklm] hash = {} uniqueID = 0 x = 0 while x < list.length hash ["#{list[x].length}.#{uniqueID}"] = list[x] x += 1 uniqueID += 1 end hash.sort.each{|k, v| p "#{k}, #{v}"} =>"1.0, a" "2.1, cd" "3.2, def" "3.3, ghi" "4.4, jklm" you could then call a String#split (or something better and easier, i'm winging it here,) on the keys, to get all the words that are 3 letters long, etc... hashes of arrays certainly are cool though, and it might be fun to play with them... foo = Hash.new{|key, value| key[value] = []} foo ["rays"] = %W[alpha beta gamma] foo ["planets"] = %W[mercury venus earth mars] foo ["colors"] = %W[red orange yellow green blue indigo violet] p foo p foo.length p foo ["rays"][1] p foo ["planets"][-1] p foo ["colors"].length -j -- Posted via http://www.ruby-forum.com/.