tags:

views:

164

answers:

2

Hi guys:

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!

+2  A: 

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

Sam Saffron
it works but Chubas'way is better to do this I think!thank you!
www
+6  A: 
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?

Chubas
thank you very much! the keys are the same.
www
I like the way merge supports a block, nice one.
Sam Saffron
@scalalala: If you're satisfied that an answer has answered your question completely, don't forget to mark it as accepted.
Andrew Grimm
@Andrew Grimm how to mark it as accepted?
www
@shewei: Click on the tick icon next to the answer's score.
Andrew Grimm
@Andrew thank you
www