From: dblack@... Date: 2003-07-31T08:28:20+09:00 Subject: Re: collect_by Hi -- On Thu, 31 Jul 2003, Simon Strandgaard wrote: > On Thu, 31 Jul 2003 08:17:44 +0900, dblac wrote: > > On Thu, 31 Jul 2003, Simon Strandgaard wrote: > >> Please enligthen me :-) > [snip] > > (Another issue is that the way you've written it, h[...] will always > > return the *same* array. But that's another matter :-) You can > > circumvent that, in 1.8, with: h = Hash.new { [] } ) > > Oh.. I luckily forgot about this. Still it won't work.. > What am I doing wrong ? > > > module Enumerable > def collect_by > h = Hash.new { Array.new } # braces :-) > each{|i| h[yield(i)].push i} > h > end > end > > a = (1..10).to_a > p a.collect_by {|i| i % 2} > #=> {} Like I said, that's just a side issue :-) You're still doing the same thing: not assigning anything to any keys in the hash. You're just retrieving the default value, altering it, and throwing it away. You could use what Brett suggested, to actually do the assignments: h = Hash.new {|hash,key| hash[key] = []} David -- David Alan Black home: dblack@superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav