4

This code:

[{:id => 1,:key => 3},{:id => 2,:key => 4},{:id => 3, :key => 5}].
     inject(Hash.new([])){|h,i| h[i[:key]] << i; h}

returns:

{}

While this:

[{:id => 1,:key => 3},{:id => 2,:key => 4},{:id => 3, :key => 5}].
     inject(Hash.new([])){|h,i| h[i[:key]] += [i]; h}

returns:

{3=>[{:id=>1, :key=>3}, {:id=>3, :key=>3}], 4=>[{:id=>2, :key=>4}]}

Why doesn't the first case work same way?

Pavel K.
  • 6,697
  • 8
  • 49
  • 80

1 Answers1

5

In your first example, you are modifying the array that is returned as the default of the hash, but that array is not defined as the value to the hash, and is thrown away.

In your second example, you are modifying the default array as well as assigning the result as the value to the hash by the method Hash#[]=. Notice that foo += bar is syntax sugar for foo = foo + bar, which means that hash[foo] += bar is the same as hash[foo] = hash[foo] + bar.

sawa
  • 165,429
  • 45
  • 277
  • 381