嵌套在Ruby中的块中的无限循环

时间:2014-09-27 10:11:44

标签: ruby arrays iteration block

这就是我要做的事情。我遍历一个字符串数组,每个字符串可能多次包含[]个字符串。我想根据需要多次使用String#match来处理每一次事件。所以我有一个Array#每个块,并且嵌套在其中是一个无限循环,只有在我用完给定字符串的匹配时才会中断。

def follow(c, dir)
  case c
    when "\\"
        dir.rotate!
    when "/"
        dir.rotate!.map! {|x| -x}
  end
  return dir
end

def parse(ar)
  ar.each_with_index { |s, i|
  idx = 0
  while true do
    t = s.match(/\[[ ]*([a-zA-Z]+)[ ]*\]/) { |m|
      idx = m.end 0
      r = m[1]
      s[m.begin(0)...idx] = " "*m[0].size
      a = [i, idx]
      dir = [0, 1]
      c = ar[a[0]][a[1]]
      while !c.nil? do
        dir = follow c, dir
        ar[a[0]][a[1]] = " "
        a[0] += dir[0]; a[1] += dir[1]
        c = ar[a[0]][a[1]]
        if c == ">" then
          ar[a[0]][a[1]+1] = r; c=nil
        elsif c == "<" then
          ar[a[0]][a[1]-r.size] = r; c=nil
        end
      end
      ar[a[0]][a[1]] = " "
      puts ar
   }
   if t == nil then break; end
   end
}
parse File.new("test", "r").to_a

测试内容:

   +--------+----------+-------------+
   | Colors |  Foods   |  Countries  |
   +--------+----------+-------------+
   | red    | pizza    | Switzerland |
 /-->     /---->       |             |
 | |[kale]/ | hot dogs | Brazil      |
 | |     <----------------------\    |
 | | orange |[yellow]\ | [green]/    |
 | +--------+--------|-+-------------+
 \-------------------/

目标:

   +--------+----------+-------------+
   | Colors |  Foods   |  Countries  |
   +--------+----------+-------------+
   | red    | pizza    | Switzerland |
     yellow   kale     |             |
   |        | hot dogs | Brazil      |
   | green                           |
   | orange |          |             |
   +--------+-------- -+-------------+

程序的实际输出:

   +--------+----------+-------------+
   | Colors |  Foods   |  Countries  |
   +--------+----------+-------------+
   | red    | pizza    | Switzerland |
     yellow          kale      |             |
   |        | hot dogs | Brazil      |
   |     <----------------------\    |
   | orange |          | [green]/    |
   +--------+-------- -+-------------+

(由于数组已经就地修改,我认为不需要更新匹配索引。)内部循环再次运行我找到的每对[],但相反,每个数组条目只有一个回合。 (似乎t=match...位不是问题,但我可能错了。)我该如何解决这个问题?

0 个答案:

没有答案