O'Reilly logo

Ruby by Example by Kevin C. Baird

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

#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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required