简体   繁体   中英

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

[{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)

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] } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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