我有两个数组:
@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 %>
提前感谢~
我有两个数组:
@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 %>
提前感谢~
您可以使用数组交集来完成此操作:
@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 %>
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
首先,您只需将两个数组相加即可。
@array_sum = @array1 + @array2
output = [a,b,c,d,e,d,e,f,g,h]
@array_sum.dub_hash => {d => 2, e => 2}
或者查看这个如何在Ruby数组中计算重复项