红宝石:2比较阵列的比赛,并计算匹配实例的数量 [英] Ruby: Compare 2 arrays for matches, and count the number of match instances

查看:126
本文介绍了红宝石: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 %>

这篇关于红宝石:2比较阵列的比赛,并计算匹配实例的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆