2哈希:
h1 = { "s1" => "2009-7-27", "s2" => "2010-3-6", "s3" => "2009-7-27" }
h2 = { "s1" => "12:29:15", "s2" => "10:00:17", "s3" => "12:25:52" }
我想将这两个哈希合并为:
h = { "s1" => "2009-7-27 12:29:15",
"s2" => "2010-3-6 10:00:17",
"s3" => "2009-7-27 2:25:52" }
这样做的最佳方式是什么?谢谢!
答案 0 :(得分:35)
h = h1.merge(h2){|key, first, second| first + " " + second }
如果您的密钥相同,它将起作用。在你的代码中,它们不是(“s1”vs“s1 =”)。它们应该是相同的键吗?
答案 1 :(得分:3)
你的意思是:
Hash[h1.map{|k,v| [k, "#{v} #{h2[k]}"]}]
=> {"s3"=>"2009-7-27 12:25:52", "s1"=>"2009-7-27 12:29:15", "s2"=>"2010-3-6 10:00:17"}
注意哈希是无序的,如果你想要一个有序的哈希,你可能需要查看at this