Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have 2 arrays:

@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)?

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

Thanks in advance~

like image 961
thedeepfield Avatar asked Feb 16 '11 07:02

thedeepfield


People also ask

How do you compare two arrays in Ruby?

Arrays can be equal if they have the same number of elements and if each element is equal to the corresponding element in the array. To compare arrays in order to find if they are equal or not, we have to use the == operator.

How do you compare numbers in two arrays?

Using Arrays. equals(array1, array2) methods − This method iterates over each value of an array and compare using equals method. Using Arrays. deepEquals(array1, array2) methods − This method iterates over each value of an array and deep compare using any overridden equals method.

Can you compare two arrays?

Programmers who wish to compare the contents of two arrays must use the static two-argument Arrays. equals() method. This method considers two arrays equivalent if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equivalent, according to Object.


1 Answers

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:

<% if [email protected]? %>   <%= @intersection.size %> Matches Found. <% else %>   No Matches Found. <% end %> 
like image 157
Pan Thomakos Avatar answered Sep 25 '22 00:09

Pan Thomakos