1

你能有一个有两个索引的 ruby​​ for 循环吗?IE:

 for i,j in 0..100
     do something
 end

在谷歌中找不到任何东西

编辑:添加更多细节

我需要像这样比较两个不同的数组

Index:  Array1:  Array2:

   0       a        a
   1       a        b
   2       a        b 
   3       a        b
   4       b        b
   5       c        b
   6       d        b
   7       d        b
   8       e        c
   9       e        d
   10      e        d
   11               e
   12               e

但是知道它们都有相同的项目(abcde)这是我的伪逻辑,让我们假设整个事情都在一个循环中

#tese two if states are for handling end-of-array cases
If Array1[index_a1] == nil
    Errors += Array1[index_a1-1]
    break
If Array2[index_a1] == nil
    Errors += Array2[index_a2-1]
    break

#this is for handling mismach
If Array1[index_a1] != Array2[index_a2]

    Errors += Array1[index_a1-1] #of course, first entry of array will always be same

    if Array1[index_a1] != Array1[index_a1 - 1]
         index_a2++ until Array1[index_a1] == Array2[index_a2]
         index_a2 -=1 (these two lines are for the loop's sake in next iteration)
         index_a1 -=1

    if Array2[index_a2] != Array2[index_a2 - 1]
         index_a1++ until Array1[index_a1] == Array2[index_a2]
         index_a2 -=1 (these two lines are for the loop's sake in next iteration)
         index_a1 -=1

简而言之,在上面的示例中,

 Errors looks like this
 a,b,e

因为 c 和 d 都很好。

4

3 回答 3

3

您可以使用枚举器而不是数字索引来迭代两个数组。此示例同时迭代a1a2回显以 ina2对应字母开头的第一个单词a1,跳过 in 中的重复项a2

a1 = ["a", "b", "c", "d"]
a2 = ["apple", "angst", "banana", "clipper", "crazy", "dizzy"]

e2 = a2.each
a1.each do |letter|
  puts e2.next
  e2.next while e2.peek.start_with?(letter) rescue nil
end

(它假设所有字母a1都至少有一个单词,a2并且都已排序——但你明白了。)

于 2012-05-17T15:07:30.233 回答
2

for 循环不是在 Ruby 中遍历数组的最佳方法。随着你的问题的澄清,我认为你有一些可能的策略。

你有两个数组,a 和 b。如果两个数组的长度相同:

a.each_index do |index|
 if a[index] == b[index]
   do something
 else
   do something else
 end
end

如果 A 比 B 短,这也有效。

如果你不知道哪个更短,你可以这样写:

controlArray = a.length < b.length ? a : b要分配 controlArray,请使用 controlArray.each_index。或者你可以(0..[a.length, b.length].min).each{|index| ...}用来完成同样的事情。


查看您对问题的编辑,我想我可以这样改写:给定一个包含重复项的数组,我如何获得每个数组中每个项目的计数并比较计数?在你的情况下,我认为最简单的方法是这样的:

a = [:a,:a,:a,:b,:b,:c,:c,:d,:e,:e,:e]
b = [:a,:a,:b,:b,:b,:c,:c,:c,:d,:e,:e,:e]
not_alike = []
a.uniq.each{|value| not_alike << value if a.count(value) != b.count(value)}
not_alike

运行该代码给了我[:a,:b,:c].

如果 a 可能不包含每个符号,那么您将需要一个仅包含符号的数组并使用它而不是 a.uniq,并且and条件中的另一个语句可以处理 nil 或 0 计数。

于 2012-05-17T17:20:47.683 回答
0

这两个数组实际上是相同的,除了我必须偶尔/或每隔一段时间跳过一些元素

您可以预先选择不可跳过的,而不是在迭代期间跳过吗?

a.select{ ... }.zip( b.select{ ... } ).each do |a1,b1|
  # a1 is an entry from a's subset
  # b1 is the paired entry bfrom b's subset
end
于 2012-05-17T17:23:28.977 回答