gpt4 book ai didi

ruby - 包含 .each_line 的 ruby​​ 循环中的高级行号

转载 作者:太空宇宙 更新时间:2023-11-03 18:25:32 26 4
gpt4 key购买 nike

这可能是一个更一般的编程问题,但我想知道 ruby​​ 解决这个问题的最佳实践是什么。我想解析具有如下结构的文件:

toplevel blah blah 0
attr0: foo
attr1: bar
nextlevel something 0
child0: baz
child1: boz
var1: blah
nextlevel something 1
child0: faz
abc: yes
child1: foz

我考虑过使用拆分并解析出 block ,或者可能使用 .each_line 遍历文件,然后以某种方式(我不知道如何)进行嵌套迭代

嵌套行,我想,看起来像这样:

input.each_line do |line|
#parse attributes
if line =~ /nextlevel:\s+(\d)/ then
#now advance the line count somehow and continue parsing in here
end

附言抱歉,如果示例中的名称有点困惑,但我试图想出一个简化的 MWE。

最佳答案

这是您要提取的排序结构吗?

def parse(inp, level)
until inp.eof?
line = inp.gets
if line =~ /nextlevel:\s+(\d)/
parse(inp, $1.to_i)
else
puts "got line: '#{line.strip}' at level #{level}"
end
end
end

irb(main):070:0> parse(input, -1)
got line: 'toplevel: 0' at level -1
got line: 'attr0: foo' at level -1
got line: 'attr1: bar' at level -1
got line: 'child0: baz' at level 0
got line: 'child1: boz' at level 0
got line: 'child0: faz' at level 1
got line: 'child1: foz' at level 1
=> nil

这使用递归方法通过堆栈跟踪深度,但使用变量和迭代方法也同样简单。

关于ruby - 包含 .each_line 的 ruby​​ 循环中的高级行号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11768232/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com