Ruby - keys of one hash into values of another hash

二次信任 提交于 2020-01-05 09:36:28

问题


I have to hashes like so:

hash1 = {
   "a" => 1,
   "b" => 1,
   "c" => 1,
   "d" => 1
}

hash2 = {
  "1" => 1,
  "2" => 1,
  "3" => 1,
  "4" => 1
}

And I need to merge them so I end up with this:

hash1 = {
  "a" => "1",
  "b" => "2",
  "c" => "3",
  "d" => "4"
}

But I don't know where to begin. Help appreciated.


回答1:


You can try the following:

Hash[hash1.keys.zip(hash2.keys)]

At first, you get array of keys for each hash with hash1.keys and hash2.keys:

["a", "b", "c", "d"]
["1", "2", "3", "4"]

Secondly, you create an array of arrays with hash1.keys.zip(hash2.keys):

[["a", "1"], ["b", "2"], ["c", "3"], ["d", "4"]]

Then with Hash[<...>] you create a Hash where the first value from the first inner array goes as key and the second as value:

{"a"=>"1", "b"=>"2", "c"=>"3", "d"=>"4"}

Example



来源:https://stackoverflow.com/questions/28511878/ruby-keys-of-one-hash-into-values-of-another-hash

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!