可能重复:
How to count duplicates in Ruby Arrays
Ruby: Compare 2 arrays for matches, and count the number of match instances
我开始使用 ruby 语言。假设我有两个数组:
a=["A", "B", "C", "D"]
b=["C", "A", "X", "Y", "F"]
我想计算两个数组中重复元素的数量。为实现这一目标,我提出的想法如下:
nr_of_duplicates = (a- (a - b)).size
有没有更好的方法来实现这一目标?
答案 0 :(得分:3)
在Array类中已经定义了一个名为'& '的方法:
ary & other_ary → new_ary
Set Intersection—Returns a new array containing elements common to the two arrays, with no duplicates.
[ 1, 1, 3, 5 ] & [ 1, 2, 3 ] #=> [ 1, 3 ]