2006年 11月 22日

Hash merge

require 'pp'

class Hash
	def deep_merge(other)
		deep_proc = Proc.new { |k, s, o|
			if s.kind_of?(Hash) && o.kind_of?(Hash)
				next s.merge(o, &deep_proc)
			end
			next o
		}
		merge(other, &deep_proc)
	end
end

a = {
	:hoge => 'hoge',
	:fuga => {
		:aaaa => 'aaaa',
		:bbbb => 'bbbb',
		:dddd => {
			:test => 'test',
		}
	},
}

b = {
	:hoge => 'hoge',
	:hage => 'ore',
	:fuga => {
		:bbbb => 'baka',
		:cccc => 'remon',
		:dddd => {
			:TTst => 'test',
		}
	},
}

pp a.merge(b)
pp a.deep_merge(b)
:!/usr/bin/ruby tmp/test.rb                                                                                                                                                   
{:hoge=>"hoge",
 :hage=>"ore",
 :fuga=>{:bbbb=>"baka", :dddd=>{:TTst=>"test"}, :cccc=>"remon"}}
{:hoge=>"hoge",
 :hage=>"ore",
 :fuga=>
  {:aaaa=>"aaaa",
   :bbbb=>"baka",
   :dddd=>{:TTst=>"test", :test=>"test"},
   :cccc=>"remon"}}

みたいなのって AS にもあったりするのかな