【发布时间】:2021-07-28 03:23:23
【问题描述】:
我正在尝试合并两个哈希数组 arr1 和 arr2:
arr1 = [{"id"=>1, "a"=>1, "c"=>2}, {"id"=>2, "a"=>1}]
arr2 = [{"id"=>1, "a"=>10, "b"=>20}, {"id"=>3, "b"=>2}]
我希望结果包含两个数组中的所有元素,但是对于“id”键具有相同值的元素应该合并,以便如果两个哈希中都存在一个键,则应该从 arr2 中选择它, 否则,它只会从密钥所在的任何哈希中选择值。因此,上面示例的组合将是:
combined = [
{"id"=>1, "a"=>10, "b"=>20, "c"=>2}, # "id"=>1 exists in both, so they are merged
{"id"=>2, "a"=>1},
{"id"=>3, "b"=>2}
]
下面的代码有效,但我是 Ruby 新手,我确信有更好的方法来做到这一点。你能提供一个更 ruby-ic 的方式吗?
combined = []
# merge items that exist in both and add to combined
arr1.each do |a1|
temp = arr2.select {|a2| a2["id"] == a1["id"]}[0]
if temp.present?
combined << temp.reverse_merge(a1)
end
end
# Add items that exist in arr1 but not in arr2
arr1.each do |a1|
if arr2.pluck("id").exclude? a1["id"]
combined << a1
end
end
# Add items that exist in arr2 but not in arr1
arr2.each do |a2|
if arr1.pluck("id").exclude? a2["id"]
combined << a2
end
end
【问题讨论】:
-
在下面查看我的答案
标签: ruby-on-rails ruby