How do I remove carriage returns with Ruby?

Use String#strip

Returns a copy of str with leading and trailing whitespace removed.

e.g

"    hello    ".strip   #=> "hello"   
"\tgoodbye\r\n".strip   #=> "goodbye"

Using gsub

string = string.gsub(/\r/," ")
string = string.gsub(/\n/," ")

Generally when I deal with stripping \r or \n, I'll look for both by doing something like

lines.gsub(/\r\n?/, "\n");

I've found that depending on how the data was saved (the OS used, editor used, Jupiter's relation to Io at the time) there may or may not be the newline after the carriage return. It does seem weird that you see both characters in hex mode. Hope this helps.


If you are using Rails, there is a squish method

"\tgoodbye\r\n".squish => "goodbye"

"\tgood \t\r\nbye\r\n".squish => "good bye"