From: Greg Hauptmann Date: 2008-10-27T12:47:57+09:00 Subject: Re: Hash.merge_add! extension - how does this code look? ------=_Part_10626_15927320.1225079299401 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Content-Disposition: inline thanks for highlighting this! Is the quickest way to normalise to Array via the following? hashitem.instance_of?(Array) ? hashitem : [hashitem] On Mon, Oct 27, 2008 at 7:45 AM, Stefan Rusterholz wrote: > Greg Hauptmann wrote: > > Hi, I wanted a way to be able to "add" values to a Hash such that it > > keeps the old and the new values. For examples example adding > > an item to a hash for which the keys are dates. Here's a first cut. > > Any feedback on coding style etc? > > Reading your problem and code I think you missed that Hash#merge > optionally takes a block which seems to solve your issue just fine but > in a more generic manner: > > hash = {'foo' => 'bar1'} > hash.merge! 'foo' => 'bar2' do |key, existing, new| > Array(existing) + [new] > end > p hash # -> {"foo"=>["bar1", "bar2"]} > > Additionally I would normalize all values to arrays upfront here, makes > dealing with the hash a lot easier. > > Regards > Stefan > -- > Posted via http://www.ruby-forum.com/. > > ------=_Part_10626_15927320.1225079299401--