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 =“input.txt”, “r”)
outfile =“output.txt”, “w”)
infile.each_line {

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

case spaces
when 1
output= “onespace”

when 2
output=“2 spaces”


outfile.write output


outfile =“output.txt”, “r”)
outfile.each_line {
print “>>”, i