Ruby 在 while 循环中忘记了局部变量? [英] Ruby forgets local variables during a while loop?

查看:81
本文介绍了Ruby 在 while 循环中忘记了局部变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个基于记录的文本文件:所以我正在寻找一个构成记录开始的起始字符串:没有记录结束标记,所以我使用下一条记录的开始分隔最后一条记录.

I'm processing a record-based text file: so I'm looking for a starting string which constitutes the start of a record: there is no end-of-record marker, so I use the start of the next record to delimit the last record.

所以我已经构建了一个简单的程序来做到这一点,但我看到一些让我吃惊的事情:看起来 Ruby 忘记了局部变量的存在 - 或者我发现了一个编程错误?[虽然我不认为我有:如果我在循环之前定义变量消息",我看不到错误].

So I have built a simple program to do this, but I see something which suprises me: it looks like Ruby is forgetting local variables exist - or have I found a programming error ? [although I don't think I have : if I define the variable 'message' before my loop I don't see the error].

这是一个简单的例子,在注释中包含示例输入数据和错误消息:

Here's a simplified example with example input data and error message in comments:

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)
#

推荐答案

我认为这是因为消息是在循环内部定义的.在循环迭代结束时,消息"超出范围.在循环之外定义消息"会阻止变量在每次循环迭代结束时超出范围.所以我认为你有正确的答案.

I think this is because message is defined inside the loop. At the end of the loop iteration "message" goes out of scope. Defining "message" outside of the loop stops the variable from going out of scope at the end of each loop iteration. So I think you have the right answer.

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

You could output the value of message at the beginning of each loop iteration to test whether my suggestion is correct.

这篇关于Ruby 在 while 循环中忘记了局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆