2
votes

I have two hashes with the same keys

{1=>2, 2=>450, 3=>3}

and

{1=>'1232', 2=>'ffsa', 3=>'vdsvds'}

I want to merge them to this

{
  1=> {:number => 2, :string => '1232'},
  2=>{:number => 450, :string => 'ffsa'}, 
  3=>{:number => 3, :string => 'vdsvds'}
}

getting values for subkey 'number' from the first hash and values for subkey 'string' from the second hash. What is the best way to achieve this?

1
Considering that @Arup's answer is the only one offered, and you seem to like it, you should consider checkmarking it.Cary Swoveland

1 Answers

8
votes

Here is a way :

h1 = {1=>2, 2=>450, 3=>3}
h2 = {1=>'1232', 2=>'ffsa', 3=>'vdsvds'}

h1.merge(h2) { |_, o, n| { number: o, string: n } }
# => {
#      1=>{:number=>2, :string=>"1232"},
#      2=>{:number=>450, :string=>"ffsa"},
#      3=>{:number=>3, :string=>"vdsvds"}
#     }