String#squish()

Note: This is included in Rails as of changesets 8878 and 9015.

If you're like me, you don't like long lines in your Ruby source code. But when a long line is needed, the alternative is string concatenation, which is even more annoying.

The alternative I present here is a very short snippet, but I've found it to be so useful that I decided to share. Thanks goes to Stephen Touset for the obscure method name, which is a lot cooler (if a little more obscure) than my previous to_line().

Usage:

@description = %{ String#squish() allows me to write long strings
  inside my Ruby code, without having to worry about indentation,
  the page margin, spaces, tabs or newlines. "double" or 'single'
  quotes are both fine, and #{interpolation} works. }.squish

Code:

class String
  # Replaces all consecutive whitespace in the string with a single
  # space, returning a one-line string, much like HTML broswers do.
  def squish
    dup.squish!
  end

  # Performs a destructive squish.
  def squish!
    strip!
    gsub! /\s+/, ' '
    self
  end
end