h1 = { "a" => 100,"b"=> 11 } h2 = { "b" => 99, "c" => 23 } 怎样把 h1、h2 两个哈希合并成{ "a"=> [100,0] , "b"=>[11,99] , "c"=>[0,23] }?求教!!
h1 = { "a" => 100,"b"=> 11 }
h2 = { "b" => 99, "c" => 23 }
h1 = { "a" => 100,"b"=> 11 } h2 = { "b" => 99, "c" => 23 } resu = h1.merge h2 resu.each_key do |x| resu[x] = [] resu[x] << (h1[x] || 0) resu[x] << (h2[x] || 0) end p resu
回复#1 楼 @chenge 略屌。
h1 = { 'a' => 100, 'b' => 11 } h2 = { 'b' => 99, 'c' => 23 } res = Hash.new{|h, k| h[k] = [0, 0]} h1.each{|k, v| res[k][0] = v} h2.each{|k, v| res[k][1] = v} p res
回复 3 楼 @reus 更短了!厉害!
Hash[(h1.keys|h2.keys).collect{|k| [k, [h1[k] || 0, h2[k] ||0]]}]
厉害~
#5 楼 @doitian 。。。。。。。目测完胜