From: "Brett H. Williams" Date: 2003-07-31T07:27:39+09:00 Subject: Re: collect_by On Jul 31, dblack@superlink.net wrote: > Hi -- > > On Thu, 31 Jul 2003, Simon Strandgaard wrote: > > > Great idea. > > > > I were just experimenting, when I discovered a glitch in > > my understanding of Ruby.. > > > > What is the difference between 'Enumerable1' and 'Enumerable'. > > Why does the 'Enumerable' work and the other not ??? > > > > Please enligthen me :-) > > > > > > module Enumerable1 > > def collect_by > > h = Hash.new [] > > each{|i| h[yield(i)].push i} > > h > > end > > end > > [...] > > # Enumerable1 > > #=> {} > > What you're seeing is a result of the fact that fetching a default > value for a hash does not actually set the key for the hash -- > because, by definition, the default value is what you get when you use > a non-existent key, and it doesn't imply assignment. For example: > > irb(main):001:0> h = Hash.new("hi") > {} > irb(main):002:0> h[1] > "hi" > irb(main):003:0> h > {} > > (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 { [] } ) Yes, my very favorite 1.8 line: h = Hash.new { |hash,key| hash[key] = [] }