对于每个增加数组的循环

时间:2015-03-04 18:35:58

标签: ruby arrays foreach

我试图使用for ruby​​中的每个循环迭代一个数组,但是在循环内部我有条件地增加了数组的大小。我想遍历数组,直到我用数组中的每个元素运行迭代,包括我添加的所有元素

for x in fol
    t = get_transition(x,"")
    for i in t
        if i != nil && !fol.include?(i)
            fol = fol.push(i)
            fol = fol.flatten
        end
    end
end

在此代码的第一个循环中,数组

fol = [1]

并将元素3添加到数组创建

fol = [1, 3]

然后再次运行循环,x = 3,数组变为

fol = [1, 3, 2]

但它不会再次迭代x = 2。 提前感谢您的任何帮助

为了澄清目的,我在print语句中添加了它们生成的输出。

fol.each do |x|
    puts "fol = #{fol}"
    puts "x = #{x}"
    t = get_transition(x,"")
    puts "t = #{t}"
    t.each do |i|
        puts "i = #{i}"
        if i != nil && !fol.include?(i)
            fol = fol.push(i)
            fol = fol.flatten
        end
    end
end

puts "\nfol = #{fol}"

此代码生成此输出

fol = [1]
x = 1
t = [3]
i = 3
fol = [1, 3]
x = 3
t = [2]
i = 2

fol = [1, 3, 2]

1 个答案:

答案 0 :(得分:3)

  

我正在尝试使用for ruby​​中的每个循环遍历数组   但是在循环内部我增加了数组的大小   有条件的。我想遍历数组直到我运行   迭代包含数组中的每个元素,包括所有元素   已添加

为什么不将此视为队列?这就是你所描述的

queue = fol.clone
until queue.empty?
  x = queue.pop
  t = get_transition(x,"")
  for i in t
    if i != nil && !fol.include?(i)
       # Not too sure what type "i" is here, but you push onto the queue here
       # I'd try to avoid flattening if you know what your data types are as it will be slow
    end
  end
end
相关问题