the*_*eld 26 ruby arrays ruby-on-rails
我有2个数组:
@array1 = [a,b,c,d,e]
@array2 = [d,e,f,g,h]
Run Code Online (Sandbox Code Playgroud)
我想比较两个数组以找到匹配(d,e)并计算找到的匹配数(2)?
<% if @array2.include?(@array1) %>
# yes, but how to count instances?
<% else %>
no matches found...
<% end %>
Run Code Online (Sandbox Code Playgroud)
提前谢谢〜
Pan*_*kos 70
您可以使用数组交集执行此操作:
@array1 = ['a', 'b', 'c', 'd', 'e']
@array2 = ['d', 'e', 'f', 'g', 'h']
@intersection = @array1 & @array2
Run Code Online (Sandbox Code Playgroud)
@intersection现在应该是['d','e'].然后,您可以执行以下操作:
<% if !@intersection.empty? %>
<%= @intersection.size %> Matches Found.
<% else %>
No Matches Found.
<% end %>
Run Code Online (Sandbox Code Playgroud)