June 2007
Intermediate to advanced
294 pages
8h 6m
English
Sometimes you may have a text file that you want to perform whitespace compression on, such as converting all repeated spaces into a single space. The script below assumes that all double line breaks should be preserved and that all single line breaks should be converted into spaces. Each group of repeated spaces should also be converted into a single space. Let’s dive right in.
#!/usr/bin/env ruby
# softwrap.rb
=begin rdoc
"Softwrap" a filename argument, preserving "\n\n"
between paragraphs but compressing "\n" and other
whitespace within each paragraph into a single space.
=end
❶ def softwrap(filename)
❷ File.open(filename, 'r').readlines.inject('') do |output,line| The inject Method ❸ output ...Read now
Unlock full access