# Stetecting change in number of leading spaces while looping

**URL:** <https://www.ruby-forum.com/t/stetecting-change-in-number-of-leading-spaces-while-looping/186120>\
**Category:** Ruby\
**Created:** [March 31, 2010, 8:35pm UTC](https://www.ruby-forum.com/t/stetecting-change-in-number-of-leading-spaces-while-looping/186120 "2010-03-31T20:35:02Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![xtremebain](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/x/a6a055/32.png) [@xtremebain](https://www.ruby-forum.com/u/xtremebain)\
**Post date:** [March 31, 2010, 8:35pm UTC](https://www.ruby-forum.com/t/stetecting-change-in-number-of-leading-spaces-while-looping/186120/1 "2010-03-31T20:35:02Z")

</div>

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  
}
