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 开发者_如何学JAVAmatches found...
<% end %>
Thanks in advance~
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 !@intersection.empty? %>
<%= @intersection.size %> Matches Found.
<% else %>
No Matches Found.
<% end %>
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.
a1 = ['a','b','c','d','d','d']
a2 = ['a','d']
superset = (a1 + a2)
subset = superset.uniq
matches = superset.count - subset.count
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
精彩评论