From: William James Date: 2005-10-14T07:46:55+09:00 Subject: Re: A (minor) coding challenge rubyhacker@gmail.com wrote: > I knew somebody would bring that up. :) > > My gut feeling is that a page break can take the place > of an arbitrary number of newlines. So I guess that means > they are "consumed" in the page break. Additionally it > seems "wrong" to start a page with blank lines. > > The only reason for preserving the extra blank lines is > in case the text happened to use them significantly, e.g., > to separate sections or before/after an inset quotation. > Lines_per_page = 60 # Read and parse a file. def grab( i ) IO.read( ARGV[i] ).split( /^((?:[ \t]*\n)*[ \t]*\n)/ ).map{ |s| s.scan( /.*?\n|.+$/ ) } end texts = grab(0).zip(grab(1)).inject([]){ |arr,pair| m = [ pair.first.size, pair.last.size ].max if pair.first.first =~ /\S/ # Equalize lengths of parallel paragraphs. 2.times { |i| pair[i] += Array.new( m - pair[i].size ) { "" } } arr << pair else # Equalize runs of blank lines and make them breakable. m.times { arr << [ [""], [""] ] } end arr } class Array def page_break each { |handle| handle.puts "----" } end end handles = [] 2.times {|i| handles << File.open( "out-junk#{ i }", "w" ) } count = 0 texts.each { |x| psize = x.first.size # Print paragraph or blank line. if psize > Lines_per_page - count handles.page_break count = 0 end # Don't print blank lines at top of page. if count > 0 or x.first.first =~ /\S/ 2.times { |i| handles[i].puts x[i] } count += psize end } handles.each { |h| h.close }