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

时间:2011-02-16 07:58:32

标签: ruby-on-rails ruby arrays

我有2个阵列:

@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 个答案:

答案 0 :(得分:67)

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

@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 :(得分: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}

或者查看此How to count duplicates in Ruby Arrays

答案 2 :(得分:0)

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

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

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

matches = superset.count - subset.count
相关问题