如何基于Rails中的哈希键合并哈希数组

如何基于Rails中的哈希键合并哈希数组

问题描述:

我想根据唯一性合并这两个数组:

I want to merge these two arrays based on uniqueness:

"template_variables": [{
    "info_top": "Some string"
}, {
    "info_bottom": "Other string"
}],


"user_variables": [{
    "info_top": "Default string"
}, {
    "info_bottom": "Other default string"
}, {
    "other_info": "Default number"
}]

所以如果我从 user_variables 数组并添加 template_variables 来替换发现匹配的散列。

So if I start with the user_variables array and add template_variables to it, replacing hashes where matches are found.

我想要的输出是:

My desired output would be:

"new_variables": [{
    "info_top": "Some string"
}, {
    "info_bottom": "Other string"
}, {
    "other_info": "Default number"
}]

我试过 user_variables.merge template_variables)及其变体,但它不适用于哈希数组。

I've tried user_variables.merge(template_variables) and variations on that, but that's not suitable for an array of hashes, it seems.

如何做到这一点?

(first_array + second_array).uniq{|hash| hash.keys.first}

但是您的数据结构很糟糕。

but your data structure sucks.