Quantcast
Channel: Active questions tagged ruby - Stack Overflow
Viewing all articles
Browse latest Browse all 4622

Ruby forgets local variables during a while loop?

$
0
0

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.

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

Viewing all articles
Browse latest Browse all 4622


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>