如何合并这两个哈希数组没有键?

时间:2012-08-18 21:10:04

标签: ruby arrays hash

我有以下哈希数组:

>> hash = { "One" => [{"Oneone" => "1", "Onetwo" => "2"}, {"Oneone" => "3", "Onetwo" => "4"}], "Two" => [{"Twoone" => "5", "Twotwo" => "6"}, {"Twoone" => "7", "Twotwo" => "8"}] }
{
    "One" => [
        [0] {
            "Oneone" => "1",
            "Onetwo" => "2"
        },
        [1] {
            "Oneone" => "3",
            "Onetwo" => "4"
        }
    ],
    "Two" => [
        [0] {
            "Twoone" => "5",
            "Twotwo" => "6"
        },
        [1] {
            "Twoone" => "7",
            "Twotwo" => "8"
        }
    ]
}

我想合并它们来实现这个目标:

{
    "OneTwo" => [
        [0] {
            "Oneone" => "1",
            "Onetwo" => "2",
            "Twoone" => "5",
            "Twotwo" => "6"
        },
        [1] {
            "Oneone" => "3",
            "Onetwo" => "4",
            "Twoone" => "7",
            "Twotwo" => "8"
        }
    ]
}

1 个答案:

答案 0 :(得分:1)

假设您的示例代表您的数据,这应该有用。

Hash[hash.keys.join,
     hash.values.transpose.map { |hashes| hashes.inject &:merge }
    ]