The Nightstar Zoo
http://zoo.nightstar.net/

Loop Refactoring?
http://zoo.nightstar.net/viewtopic.php?f=90&t=14552
Page 1 of 1

Author:  Chalain [ Wed Feb 08, 2006 3:23 pm ]
Post subject:  Loop Refactoring?

So, I have a loop that has a precondition and a post condition, and the loop body includes both of these. E.g. the loop goes
Code:
step 1
begin loop
  step 2
  step 1
end loop
step 2


I think it looks horribly inelegant. How do I clean this up?

Code:
# This is mostly pseudoruby.  I don't expect this to pass a syntax checker.
# find all lines beginnig with a '.' and splice them onto the previous line
open input_file
open output_file

prev_line = curr_line = ''
prev_line = input_file.get_line()
while curr_line = input_file.get_line() != File.EOF
  if curr_line =~ /^\s*\./
    prev_line += curr_line
  else
    output_file.write(prev_line)
    prev_line = curr_line
  end
end
output_file.write(prev_line)
close input_file
close output_file


Any ideas?

Author:  SomebodyElse [ Wed Feb 08, 2006 11:37 pm ]
Post subject:  Re: Loop Refactoring?

Is there any way to suppress the automatic newline during "output_file.write()"? Then, you could do:

Code:
# Note: I know absolutely nothing about Ruby.  The following code may be horribly incorrect.

open input_file
open output_file

curr_line = input_file.get_line()
output_file.write_no_newline(curr_line)

while curr_line = input_file.get_line() != File.EOF
  if not curr_line =~ /^\s*\./
    output_file.write('')    # Write a newline.
  end

  output_file.write_no_newline(curr_line)
end

close input_file
close output_file


Then again, maybe I've been hacking C too long.

Author:  Schol-R-LEA [ Mon Feb 13, 2006 7:53 pm ]
Post subject: 

While I don't know Ruby that well, a quick look at this tutorial gives a clear solution, using a do block:

Code:
lineAccumuate = ""
File.open("output.txt", "w"), File.open("input.txt, "r").each_line do |output_file, line|
      if line.scan( /^\s*\./) then
            lineAccumulate += line
      else
            output_file.puts lineAccumulate
            lineAccumulate = line
      end
end


I'm not entirely sure you can double up the arguments of a block like I did here, but I gather it is possible. Also, I didn't use any error handling, as I've yet to read up on that aspect of the language.

Alternately, if you can guarantee that the input file is small enough to fit into memory, you could use File.readLines() to slurp the whole file in at once, and then walk through it using the array operators.

Code:
File.open("input.txt", "r") do |input_file|
      lines = input_file.readLines
end

lines.each do |curr_line|
     line Accumualate = ""
     while curr_line.scan( /^\s*\./) do
           lineAccumulate += curr_line
     end
     output_file.puts(lineAccumulate)
end

Page 1 of 1 All times are UTC - 6 hours [ DST ]
Powered by phpBB® Forum Software © phpBB Group
http://www.phpbb.com/