On 3/14/07, Giles Bowkett <gilesb / gmail.com> wrote:
> Would the correct translation of the memo solution to accomodate this
> be something like this?
>
> items.inject{|happy_output_hash, item|
> happy_output_hash.merge(item.hash_within) {|k,e,v| e + v}}

There is a subtle difference between

  hashes.inject(Hash.new {0}) {|memo, hash| memo.merge(hash) {|k,e,v| e + v}}
  hashes.inject{|memo, hash| memo.merge(hash) {|k,e,v| e + v}}

(and by extension, your suggestion above, which is a correct
adaptation of the latter).

The optional parameter to inject provides a "seed" value. If no seed value is
provided, the first element of the enumerable is used as the seed and the block
evaluated over the tail only. In most cases this won't matter, and using an
argumentless inject is hunky-dory. But there are two gotchas:

1) If the array is empty, providing no seed means that +nil+ will be used as
the seed value. Probably not what you want as you'll get a NoMethodError for
nil#merge.

2) If not all the hashes in the array have the same keys, you'll probably get
some NoMethodErrors for nil#+. That's the reason the seed hash in the former
version provides an explicit default value.

Jacob Fugal