Ruby:将两个散列合并为一个并与值相连 [英] Ruby: merge two hash as one and with value connected

查看:99
本文介绍了Ruby:将两个散列合并为一个并与值相连的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$ 2
$ b

  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}

要做到这一点的最佳方法是什么?谢谢!

解决方案

  h = h1.merge(h2){|第二|第一个++第二个)

如果您的密钥相同,在你的代码中,它们不是(s1vss1 =)。他们应该是相同的钥匙?


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="). Are they supposed to be the same keys?

这篇关于Ruby:将两个散列合并为一个并与值相连的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆