Ruby中嵌套在块中的无限循环
这就是我要做的。我正在遍历一个字符串数组,每个字符串可能多次包含[]。我希望尽可能多地使用Stringmatch来处理每次事件。所以我有一个Arrayeach块,嵌套在其中的是一个无限循环,只有当给定字符串的匹配项用完时,该循环才会中断Ruby中嵌套在块中的无限循环,ruby,arrays,iteration,block,Ruby,Arrays,Iteration,Block,这就是我要做的。我正在遍历一个字符串数组,每个字符串可能多次包含[]。我希望尽可能多地使用Stringmatch来处理每次事件。所以我有一个Arrayeach块,嵌套在其中的是一个无限循环,只有当给定字符串的匹配项用完时,该循环才会中断 def follow(c, dir) case c when "\\" dir.rotate! when "/" dir.rotate!.map! {|x| -x} end return dir end
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 |
yellow kale | |
| | hot dogs | Brazil |
| <----------------------\ |
| orange | | [green]/ |
+--------+-------- -+-------------+
由于数组已经修改到位,我认为不需要更新匹配索引。对于我找到的每一对[],内部循环应该再次运行,但相反,我每个数组条目只得到一次循环。似乎t=匹配。。。比特不是问题,但我可能错了。如何修复此问题?您的代码很难阅读。你能分享一个输入样本和预期结果吗?@Martin好的,我添加了一个测试用例、预期输出和实际输出。如果有帮助的话,这是a的一个条目。好的,代码golf解释了一些简短的变量名,非常简洁的代码。
+--------+----------+-------------+
| 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]/ |
+--------+-------- -+-------------+