From: Trans Date: 2007-03-15T06:14:27+09:00 Subject: Re: non-destructive merging of hashes in array On Mar 14, 4:49 pm, "Giles Bowkett" wrote: > The functor seems pretty cool. The sad thing is, I still have the most > primitive implementation possible in my actual code. The reason is, I > don't want to pop it in without fully understanding it. > > The memo solution looks cleanest, that's really just a gut feeling > though. Let me just make sure I get it. Here it is: > > hashes.inject{|memo, hash| memo.merge(hash) {|k,e,v| e+ v}} > > Now partly it turns out my problem is slightly more complicated. It's > not an array of hashes; it's an array of objects which can return > hashes. So it basically looks like this: > > def enter_output > @items = get_the_items > @happy_output_hash = {} > # non-destructively merge all hashes within @items into one hash > @items.each do |item| > item.hash_within.each do |key, value| > if @happy_output_hash[key] > @happy_output_hash[key] += value > else > @happy_output_hash[key] = value > end > end > end > end > > (Code altered to enhance obviousness.) > > 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}} Should work. Or you could split it into two lines if it's easier to read: hashes = items.collect{ |item| item.hash_within } > Also, what does the Functor solution actually do? That sounds Lispy, > which appeals to me, but I want to be sure the code is maintainable by > lesser mortals, such as, for example, me. (Depending on what your doing exactly) the inject/merge is probably just fine. Functor is pretty straight forward. The basic definition is: class Functor def initialize(*objs, &block) @objs = objs @block = block end def method_missing(sym,*args) @block.call(@sym,*(@objs + args)) end end T.