简体   繁体   English

Ruby:我有两个哈希数组,如何计算两个哈希中具有相同ID的元素?

[英]Ruby: I have two arrays of hashes, how do I count elements with the same id in both hashes?

I have two arrays of hashes in Ruby like 我在Ruby中有两个哈希数组

[{id: 1, a:2, b:3, c:4},{id:2, a:8, b:10, c:12}]
[{id: 1, a:3, b:8, c:9},{id:2, a:8, b:18, c:20},{id:3, a:10, b:15, c:29}]

and I want to find how many pairs of elements (one for each array) have the same id and the same a, in this case it's only one (the ones with id: 2 and a: 8) 我想找出多少对元素(每个数组一个)具有相同的ID和相同的a,在这种情况下,它只有一个(ID为2和a的元素为8)

Is there an efficient way to count this? 有没有一种有效的方法来计算?

Thanks in advance 提前致谢

a1 = [{id: 1, a:2, b:3, c:4},{id:2, a:8, b:10, c:12}]
a2 = [{id: 1, a:3, b:8, c:9},{id:2, a:8, b:18, c:20},{id:3, a:10, b:15, c:29}]

(a1.map{|h| [h[:id], h[:a]]} & a2.map{|h| [h[:id], h[:a]]}).length
# => 1

A variation that is fairly easy to extend which attributes are compared: 一个很容易扩展比较属性的变体:

x = [{id: 1, a:2, b:3, c:4},{id:2, a:8, b:10, c:12}]
y = [{id: 1, a:3, b:8, c:9},{id:2, a:8, b:18, c:20},{id:3, a:10, b:15, c:29}]

x.product(y).count { |p| [:id,:a].all? { |k| p[0][k]==p[1][k] } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM