问题
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