On Mon, 28 Aug 2000, Dave Thomas wrote:

> Brian Fundakowski Feldman <green / FreeBSD.org> writes:
> 
> > Hash.new may take an argument that specifies the default value for
> > hash members.  To do it with empty arrays, for example:
> 
> >...
> 
> > Hope it helps!
> 
> 'fraid not.
> 
> Currently the default parameter is evaluated just once, so all entries 
> will default to having the same empty array.
> 
>   h = Hash.new(Array.new)
>   h['cat'] << 'hello'
>   h['dog'] << 'goodbye'
>   puts h['cat'].inspect  #=> ["hello", "goodbye"]

Oh nuts :( That certainly doesn't show up when using integers.  Well,
fortunately, there's an easy solution, which will work with += but not
(ab)using << (which is a tad harder because you can't change self that
much, of course):

e = Array.new
def e.+(a)
	return Array.new + a
end
h = Hash.new(e)
h['cat'] += 'hello'
h['dog'] += 'goodbye'
puts h['cat'].inspect  #=> ["hello", "goodbye"]

> 
> However, there's some talk of a new syntax:
> 
>  h = Hash.new { stuff }
> 
> Where the block will be evaluated to create missing elements.

I like that idea!

> Regards
> 
> 
> Dave

--
 Brian Fundakowski Feldman           \  FreeBSD: The Power to Serve!  /
 green / FreeBSD.org                    `------------------------------'