Ruby在while循环期间会忘记局部变量?

前端之家收集整理的这篇文章主要介绍了Ruby在while循环期间会忘记局部变量?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在处理一个基于记录的文本文件:所以我正在寻找一个构成记录开始的起始字符串:没有记录结束标记,所以我使用下一个记录的开始来定义最后记录.

所以我已经建立了一个简单的程序来做到这一点,但是我看到一些令我震惊的东西:看起来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
# 
# Error when running: [nb,first iteration is fine]
# <StringIO:0x2e845ac>
# hello
# test.rb:5: undefined local variable or method `message' for main:Object (NameError)
#

解决方法

我认为这是因为在循环中定义消息.在循环结束循环“消息”超出范围.在循环之外定义“消息”会在每个循环迭代结束时停止变量超出范围.所以我认为你有正确的答案.

您可以在每次循环迭代开始时输出消息的值,以测试我的建议是否正确.

原文链接:https://www.f2er.com/ruby/273224.html

猜你在找的Ruby相关文章