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.

  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
by writing something like:

  fred = {}

  fred['hugh'] ||= []           # create entry if none there

  fred['hugh'][0] = 'hello'

  fred                          # {"hugh"=>["hello"]}


Did this make sense? I'm on the wrong side of the sleep curve at the
moment ;-)


Dave