From: Robert Klemme Date: 2010-04-01T16:52:43+09:00 Subject: Re: change in number of leading spaces 2010/4/1 Jesse B. : > Sorry about re-post due to typo. > > 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") You can simplify this by using File.foreach "input.txt" do |line| ... end > outfile = File.new("output.txt", "w") Also, please make it a habit to use the block form of File.open which is much safer. So this becomes File.open("output.txt", "w") do |outfile| ... end For some background: http://blog.rubybestpractices.com/posts/rklemme/001-Using_blocks_for_Robustness.html > 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 As Alex already pointed out this should be defined outside the loop. Here's another variant def count_leading_spaces(s) s[/\A */].length # or any other method that works end sp = 0 ARGF.each_line do |line| i = count_leading_spaces line if i != sp line.chomp! # avoid duplicate \n printf "Change from %2d to %2d spaces in this line %4d: %s\n", sp, i, ARGF.lineno, line sp = i end end Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/