rails/rails — pull request #8088 by ndbroadbent (2012-10-31 22:58:03+00:00)
Title: ActiveSupport: Added `each_with_hash` to Enumerable

This is in response to the discussion at https://bugs.ruby-lang.org/issues/7241

I think an `each_with_hash` method would be a very useful addition. It would provide a nice shortcut for the very common `each_with_object({})`, but here's the most extreme example of how I would write less code using this method:

```ruby
# each_with_object:

[1,2,3,2].each_with_object(Hash.new(&-> hash, key { hash[key] = [] })) {|el, hash| hash[el] << el ** 2 }
#=> {1=>[1], 2=>[4, 4], 3=>[9]}

# each_with_hash:

[1,2,3,2].each_with_hash([], true) {|hash, el| hash[el] << el ** 2}
#=> {1=>[1], 2=>[4, 4], 3=>[9]}
```

I would love to be able to easily use `<<` with arrays, instead of having to write `hash[el] += [el ** 2]`.

If this gets merged, it would be awesome if it could also be included in `3-2-stable`.

Thanks!