On 27 Jul 2000, Dave Thomas wrote: > Hugh Sasse Staff Elec Eng <hgs / dmu.ac.uk> writes: > > > I have a program, too large to post here, and an object in it with a > > variable: > > > > @chunks = Hash.new([]) > > What this does is to set the default value for any unknown keys at an > empty array. It will be the same array for any missing key. Aha, that it why I am getting them all the same! > > fred = Hash.new([]) # => {} > fred['dave'] # => [] > fred['hugh'] # => [] > fred['dave'][0] = 'hello' # => "hello" > fred['hugh'] # => ["hello"] !!! > > > But - having done this, I still haven't actually created any members > in the hash-all I've done is access the default value: > > fred.inspect # => "{}" > > Unlike Perl, Ruby doesn't automagically create the sub-arrays the > first time you reference one. You could do it by subclassing Hash, or OK, I'll be a bit more careful about that. > by writing something like: > > fred = {} > > fred['hugh'] ||= [] # create entry if none there > Hmm, that is cunning. :-) > fred['hugh'][0] = 'hello' > > fred # {"hugh"=>["hello"]} > > > Did this make sense? I'm on the wrong side of the sleep curve at the > moment ;-) It was spot on. thank you. > > > Dave > > Hugh hgs / dmu.ac.uk