stephen O'D
7/19/2007 9:48:00 PM
I want a hash, where the values of the keys are arrays, eg
h = Hash.new
h.default = []
h['foo'] << 10
h[foo'] << 20
h['bar'] << 23
h['bar'] << 33
I thought this would give me
{ 'foo' => [20 30],
'bar' => [23, 33] }
but it doesn't - it seems to put the same array in the value of each
key. Some googling revealed I need to create my hash like:
h = Hash.new { |hash, key| hash[key] = [] }
So my problem is solved, but why do you have to do it like this? At
the risk of answering my own question, is it because the block is re-
executed everytime you access a non existent key, creating a brand new
array object, while the first way, it just initialises the value to
the same array each time?
Thanks,
Stephen.