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

31

我有两个数组:

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

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

<% if @array2.include?(@array1) %>
  # yes, but how to count instances?
<% else %>
  no matches found...
<% end %>

提前感谢~

3个回答

81

您可以使用数组交集来完成此操作:

@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 %>

1
要找到数组之间的匹配总数,将它们加在一起,然后减去唯一集合。超集数组长度与唯一集合的差值将是第二个数组在第一个数组中匹配的计数。如果a2是唯一集,则此方法效果最佳。
a1 = ['a','b','c','d','d','d']
a2 = ['a','d']

superset = (a1 + a2)
subset = superset.uniq

matches = superset.count - subset.count

0
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数组中计算重复项


如果你有超过2个数组,这将非常有帮助。 - kriysna

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