Stetecting change in number of leading spaces while looping

I am looping through a file and using a script that detects leading
spaces (based on a previous post to this forum)

What I want to do is to detect changes in number of leading spaces, for
instance when one line has more, fewer, or the same number of leading
spaces as the previous line.

The problem I am having is with setting a value from within the loop
which is then available on the next loop.

here is an example of the program:

infile = File.new(“input.txt”, “r”)
outfile = File.new(“output.txt”, “w”)
infile.each_line {
|i|

spaces = i[/\A */].length

#the following variable “stored” puts undef every time through, which
means #it’s not retaining the value on the next loop?

if defined?(stored)== true
puts stored

elsif defined?(stored)== nil
puts “undef”
stored = spaces
end

case spaces
when 1
output= “onespace”

when 2
output=“2 spaces”

end

outfile.write output
}

outfile.close()
infile.close()

outfile = File.new(“output.txt”, “r”)
outfile.each_line {
|i|
print “>>”, i
}

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs