Ruby:比较 2 个匹配的数组,并计算匹配实例的数量 [英] Ruby: Compare 2 arrays for matches, and count the number of match instances
本文介绍了Ruby:比较 2 个匹配的数组,并计算匹配实例的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有 2 个数组:
@array1 = [a,b,c,d,e]
@array2 = [d,e,f,g,h]
我想比较两个数组以找到匹配项 (d,e) 并计算找到的匹配项数 (2)?
I want to compare the two arrays to find matches (d,e) and count the number of matches found (2)?
<% if @array2.include?(@array1) %>
# yes, but how to count instances?
<% else %>
no matches found...
<% end %>
先谢谢了~
推荐答案
你可以用数组交集来做到这一点:
You can do this with array intersection:
@array1 = ['a', 'b', 'c', 'd', 'e']
@array2 = ['d', 'e', 'f', 'g', 'h']
@intersection = @array1 & @array2
@intersection 现在应该是 ['d', 'e'].然后您可以执行以下操作:
@intersection should now be ['d', 'e']. You can then do the following:
<% if !@intersection.empty? %>
<%= @intersection.size %> Matches Found.
<% else %>
No Matches Found.
<% end %>
这篇关于Ruby:比较 2 个匹配的数组,并计算匹配实例的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文