Ruby reduce all whitespace to single spaces

Within Rails you can use String#squish, which is an active_support extensions.

require 'active_support'

s = <<-EOS
1/2 cup  

            onion
EOS

s.squish
# => 1/2 cup onion

This is a case where regular expressions work well, because you want to treat the whole class of whitespace characters the same and replace runs of any combination of whitespace with a single space character. So if that string is stored in s, then you would do:

fixed_string = s.gsub(/\s+/, ' ')

You want the squeeze method:

str.squeeze([other_str]*) → new_str
Builds a set of characters from the other_str parameter(s) using the procedure described for String#count. Returns a new string where runs of the same character that occur in this set are replaced by a single character. If no arguments are given, all runs of identical characters are replaced by a single character.

   "yellow moon".squeeze                  #=> "yelow mon"
   "  now   is  the".squeeze(" ")         #=> " now is the"
   "putters shoot balls".squeeze("m-z")   #=> "puters shot balls"

Tags:

Ruby