Ruby:比较2个匹配数组,并计算匹配实例的数量

我有2个数组:

@array1 = [a,b,c,d,e] @array2 = [d,e,f,g,h] 

我想比较两个数组以找到匹配(d,e)并计算找到的匹配数(2)?

  # yes, but how to count instances?  no matches found...  

提前谢谢〜

您可以使用数组交集执行此操作:

 @array1 = ['a', 'b', 'c', 'd', 'e'] @array2 = ['d', 'e', 'f', 'g', 'h'] @intersection = @array1 & @array2 

@intersection现在应该是[‘d’,’e’]。 然后,您可以执行以下操作:

 <% if !@intersection.empty? %> <%= @intersection.size %> Matches Found. <% else %> No Matches Found. <% end %> 
 class Array def dup_hash inject(Hash.new(0)) { |h,e| h[e] += 1; h }.select { |k,v| v > 1 }.inject({}) { |r, e| r[e.first] = e.last; r } end end 

首先,您只需添加两个数组

 @array_sum = @array1 + @array2 output = [a,b,c,d,e,d,e,f,g,h] @array_sum.dub_hash => {d => 2, e => 2} 

或者查看这个如何计算Ruby Arrays中的重复项

要查找数组之间的总匹配数,请将它们一起添加,然后减去唯一集。 超集arrays的长度与uniq集之间的差异将是第一个arrays中第二个arrays的匹配计数。 如果a2是唯一集合,则此方法效果最佳。

 a1 = ['a','b','c','d','d','d'] a2 = ['a','d'] superset = (a1 + a2) subset = superset.uniq matches = superset.count - subset.count