Managing Whitespace
Problem
Your string contains too much whitespace, not enough whitespace, or the wrong kind of whitespace.
Solution
Use strip to remove whitespace from the beginning and end of a string:
" Whitespace at beginning and end. ". strip
Add whitespace to one or both ends of a string with ljust, rjust, and center:
s = "Some text." s. center(15) s. ljust(15) s. rjust(15)
Use the gsub method with a string or regular expression to make more complex changes, such as to replace one type of whitespace with another.
#Normalize Ruby source code by replacing tabs with spaces rubyCode.gsub(" ", " ") #Transform Windows-style newlines to Unix-style newlines "Line one Line two ".gsub( ", " ") # => "Line one Line two " #Transform all runs of whitespace into a single space character " This string uses all sorts of whitespace.".gsub(/s+/," ") # => " This string uses all sorts of whitespace."
Discussion
What counts as whitespace? Any of these five characters: space, tab ( ), newline ( ), linefeed ( ), and form feed (f). The regular expression /s/ matches any one character from that set. The strip method strips any combination of those characters from the beginning or end of a string.
In rare cases you may need to handle oddball "space" characters like backspace ( or