如何匹配两个数组的内容并得到相应的索引ruby

inq*_*ive 2 ruby arrays

原始问题:最初的问题是如何迭代到嵌套循环ruby中的下一个元素.答案教会了解决我的问题的惯用方法,它需要一个不同的问题,以便当用户在google搜索时,找到正确的东西

我有这个要求,其中有两个数组,并且每个数组都按排序顺序具有唯一值.

array1 = [2,3,4,5,6,7] #can not have repeated values[2,2,3]
array2 = [2,5,7]
Run Code Online (Sandbox Code Playgroud)

我希望匹配两个数组的元素,并match found在找到匹配时打印,以及两个数组的索引.这是可以正常工作的代码.

array1.each do |arr1|
  array2.each do |arr2|
    if (arr1==arr2)
      puts ("Match found element #{arr1} #{array1.index(arr1)} #{array2.index(arr2)}")
      #some code here to move to the next element in array 1 and array 2 and continue looping from there
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

但是这并没有使用数据结构的独特性和以任何方式排序.例如,当在上述例子中,元件2array1比赛元件2array2,该元件2array2不应该继续尝试匹配的其他元件array1,也array1应该被移动到下一个.我知道有一些叫做的东西next.但我认为只返回下一个元素并且不会将迭代器移动到下一个元素?此外,我必须移动到两个阵列的下一个.我该怎么做呢?

Ale*_*Pan 5

如果要在两个数组之间找到匹配的元素,只需使用&如下:

array1 = [2,3,4,5,6,7] #does not have repeated values[2,2,3] and the values are sorted
array2 = [2,5,7]

matches = array1 & array2
 => [2, 5, 7]
Run Code Online (Sandbox Code Playgroud)

要打印在每个数组中找到的匹配和索引,只需循环遍历matches数组:

matches.each do |number|
  puts "Match found element #{number}"
  puts "array1 index=#{array1.rindex(number)}"
  puts "array2 index=#{array2.rindex(number)}"
end

Match found element 2
array1 index=0
array2 index=0
Match found element 5
array1 index=3
array2 index=1
Match found element 7
array1 index=5
array2 index=2
Run Code Online (Sandbox Code Playgroud)