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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5013880/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:26:30  来源:igfitidea点击:

Ruby: Compare 2 arrays for matches, and count the number of match instances

ruby-on-railsrubyarrays

提问by thedeepfield

I have 2 arrays:

我有 2 个数组:

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

I want to compare the two arrays to find matches (d,e) and count the number of matches found (2)?

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

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

Thanks in advance~

先谢谢了~

回答by Pan Thomakos

You can do this with array intersection:

你可以用数组交集来做到这一点:

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

@intersection should now be ['d', 'e']. You can then do the following:

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

<% if [email protected]? %>
  <%= @intersection.size %> Matches Found.
<% else %>
  No Matches Found.
<% end %>

回答by kriysna

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

First you just add both arrays

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

@array_sum = @array1 + @array2

output = [a,b,c,d,e,d,e,f,g,h]

@array_sum.dub_hash => {d => 2, e => 2}

Or check this How to count duplicates in Ruby Arrays

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

回答by vanboom

To find the number of total matches between the arrays, add them together, then subtract the unique set. The difference between the length of the superset array and the uniq set will be the count of the matches of the second array in the first. This method works best if a2 is a unique set.

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

a1 = ['a','b','c','d','d','d']
a2 = ['a','d']

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

matches = superset.count - subset.count