From: Greg Hauptmann Date: 2008-10-27T16:41:01+09:00 Subject: Re: Hash.merge_add! extension - how does this code look? I just noticed the code suggested might have a problem when the original hash is empty. That is using the ability to pass a block to 'merge!" is good, but when the source hash is empty it does not seem to trigger use of the code in the block to merge. -----code---- def merge_add!(h) self.merge!(h) do |key, existing, new| new = new.instance_of?(Array) ? new : [new] existing = existing.instance_of?(Array) ? existing : [existing] existing + new end end ------------- ---in console--- ?> {}.merge_add!({1 => 100}) => {1=>100} <<== DID NOT PUT THE '100' IN AN ARRAY!! >> {1 => 300}.merge_add!({1 => 100}) => {1=>[300, 100]} -------------- regards Greg On Mon, Oct 27, 2008 at 5:21 PM, Stefan Rusterholz wrote: > > Greg Hauptmann wrote: > > thanks for highlighting this! Is the quickest way to normalise to Array > > via > > the following? > > hashitem.instance_of?(Array) ? hashitem : [hashitem] > > If you're building up the hash yourself then I'd use the following > idiom: > collector = Hash.new { |h,k| h[k] = [] } > collector['key1'] << 'value1' > collector['key2'] << 'value1' > collector['key1'] << 'value2' > p collector > > Simplifies adding to and reading from the hash. But be aware that with > the hash having a different default value than nil, you can't use 'if > collector[key] then' to test for existence of a key anymore, you have to > use has_key?. > > If you're not building the hash up yourself, then yes, I'd use what you > wroten in an each loop and override the existing value. > > Regards > Stefan > -- > Posted via http://www.ruby-forum.com/. >