在Ruby中合并两个对象数组

3

我有一个带有唯一ID的对象数组:

[{id: 1, score: 33}, {id: 23, score: 50}, {id:512, score: 27}, ...]

我还有一个用户记录的数组,其中包含匹配的ID。这些用户记录有“name”,但没有“score”:

[{id: 1, name: "Jon"}, {id: 23, name: "Tom"}, {id: 512, name: "Joey"}, ...]

我该如何创建一个包含每个id、姓名和分数的单一数组?
[{id: 1, name: "Jon", score: 33}, {id: 23, name: "Tom", score: 50}, {id: 512, name: "Joey", score: 27}, ...]

我尝试了mergecombinefilter等方法,但是没有找到能够实现这个功能的Ruby函数。
3个回答

3
假设在用户中总是有相应于scores的记录::id
scores = [{id: 1, score: 33}, {id: 23, score: 50}, {id:512, score: 27}]
users  = [{id: 1, name: "Jon"}, {id: 23, name: "Tom"}, {id: 512, name: "Joey"}]

scores = scores.map { |score| score.merge(users.find { |user| user[:id] == score[:id] }) }
# => [{:id=>1, :score=>33, :name=>"Jon"}, {:id=>23, :score=>50, :name=>"Tom"}, {:id=>512, :score=>27, :name=>"Joey"}]

希望这能帮助你正确地理解!

有趣 - 谢谢Pawel!您是否还知道一个函数,可以让我从给定ID的分数中找到匹配的对象? - Don P
1
实际上,这就是 find(来自 Enumerable 模块,它被包含在 Array 中)所做的事情。你应该使用:scores.find { |element| element[:id] == 123 }。请查看文档以获取更多示例。希望能有所帮助! - Paweł Dawczak

1
你可以使用一个中间哈希表。
hsh = Hash[ a1.map {|h| [h[:id], h[:score]]} ]
# => {1=>33, 23=>50, 512=>27}
a2.map {|h| h[:score] = hsh[h[:id]]; h}
# => [{:id=>1, :name=>"Jon", :score=>33}, {:id=>23, :name=>"Tom", :score=>50}, {:id=>512, :name=>"Joey", :score=>27}]

我喜欢你的解决方案,但更喜欢 a2.each_with_object({}) { |g,h| h.update(g[id] => g) },因为它不会改变 a2,而且在我看来更易读。 - Cary Swoveland

1
如果像示例中一样,对于所有的iscores[i][:id] = users[i][:id],并且您正在使用v1.9+(其中键插入顺序被维护),则可以编写以下内容:
scores.zip(users).each_with_object({}) do |(sh,uh),h|
   h.update(sh).update(uh)
end

我会用这个吗?你呢?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接