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

Get Ruby by Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.