From: Brian Candler Date: 2003-07-31T08:35:22+09:00 Subject: Re: collect_by On Thu, Jul 31, 2003 at 08:14:59AM +0900, 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} > #=> {} 1. h[foo] returns a new empty array 2. you push something onto that array 3. no reference to that array is stored anywhere 4. the array disappears into the ether, to get garbage-collected at a later date The important thing is, step (1) does not assign anything to the hash. h remains as {} throughout. Regards, Brian.