我正在处理一个基于记录的文本文件:所以我正在寻找一个构成记录开头的起始字符串:没有记录结束标记,所以我使用下一条记录的开头来划分最后一项记录
所以我已经构建了一个简单的程序来实现这一点,但是我看到一些让我感到惊讶的事情:看起来Ruby似乎忘记了局部变量 - 或者我发现了编程错误?[虽然我不认为我有:如果我在循环之前定义变量'message'我没有看到错误].
这是一个简单的示例,其中包含示例输入数据和注释中的错误消息:
flag=false
# message=nil # this is will prevent the issue.
while line=gets do
if line =~/hello/ then
if flag==true then
puts "#{message}"
end
message=StringIO.new(line);
puts message
flag=true
else
message << line
end
end
# Input File example:
# hello this is a record
# this is also part of the same record
# hello this is a new record
# this is still record 2
# hello this is record 3 etc etc
#
# …Run Code Online (Sandbox Code Playgroud)