简体   繁体   English

Ruby:将两个哈希合并为一个并连接值

[英]Ruby: merge two hash as one and with value connected

2 hash: 哈希:

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" }    

I want to merge the two hash as one like this: 我想合并这两个哈希像这样:

h = { "s1" => "2009-7-27 12:29:15",
      "s2" => "2010-3-6 10:00:17", 
      "s3" => "2009-7-27 2:25:52" }

what is the best way to do this? 做这个的最好方式是什么? thanks! 谢谢!

h = h1.merge(h2){|key, first, second| first + " " + second }

It will work if your keys are the same. 如果您的密钥相同,它将起作用。 In your code, they aren't ("s1" vs "s1="). 在你的代码中,它们不是(“s1”vs“s1 =”)。 Are they supposed to be the same keys? 它们应该是相同的键吗?

You mean: 你的意思是:

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"}

Note hashes are unordered, if you want an ordered hash you probably need to look at this 注哈希是无序的,如果你想要一个有序的散列你可能需要看看这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM