#11 Wrapping Lines of Text (softwrap.rb)

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.

The Code

  #!/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.
❶ def softwrap(filename)
❷   File.open(filename, 'r').readlines.inject('') do |output,line|    The inject Method ❸ output ...

Get Ruby by Example now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.