Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: merge two hash as one and with value connected

Tags:

merge

ruby

hash

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!

like image 685
www Avatar asked May 20 '10 05:05

www


People also ask

How do you combine hashes in Ruby?

We can merge two hashes using the merge() method. When using the merge() method: Each new entry is added to the end. Each duplicate-key entry's value overwrites the previous value.

How do you combine Hash?

Hash#merge!() is a Hash class method which can add the content the given hash array to the other. Entries with duplicate keys are overwritten with the values from each other_hash successively if no block is given.

Can a Hash have multiple values Ruby?

Can a hash have multiple values Ruby? Each key can only have one value. But the same value can occur more than once inside a Hash, while each key can occur only once.

How do you know if two hashes are equal Ruby?

Equality—Two hashes are equal if they each contain the same number of keys and if each key-value pair is equal to (according to Object#== ) the corresponding elements in the other hash. The orders of each hashes are not compared. Returns true if other is subset of hash.


2 Answers

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?

like image 170
Chubas Avatar answered Sep 24 '22 13:09

Chubas


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

like image 22
Sam Saffron Avatar answered Sep 22 '22 13:09

Sam Saffron