From: Shashank Date Date: 2005-03-15T22:59:01+09:00 Subject: Re: YAML obj merging Hi Florian, Florian Gross wrote: > class Hash > # Similar to Hash#merge, but this version works recursively so that > # nested Hashs will be merged as well. You can specify a collision > # block which will be invoked for conflicting items. (It takes the > # same argument list as the collision block supplied to Hash#merge: > |hash, item1, item2|) I am not able to understand how the collision block thing will work here. Can you please give an example? I tried this, but it did not work like I expected: b.mix(a){|key,old,nu| old} #=> {"A"=>{"B1"=>"b", "A1"=>"a"}} > # > # Usage example: > # a = { "A" => { "A1" => "a" } } > # b = { "A" => { "B1" => "b" } } > # b.mix(a) # => {"A" => {"A1" => "a", "B1" => "b" }} > def mix(other, &collision_block) > merge_block = lambda do |hash, item1, item2| > if item1.is_a?(Hash) and item2.is_a?(Hash) then > item1.merge(item2, &merge_block) > elsif collision_block then When does this elsif get executed? > collision_block.call(hash, item1, item2) > else > item2 > end > end > > self.merge(other, &merge_block) > end > end > > So basically the block that Hash#merge can take is insanely useful. I've > also used for just detecting Hash collisions in the past as well. I did not know that Hash#merge could take a block. Thanks for pointing it out. -- shanko