How can I remove the string "\n" from within a Ruby string?

ben picture ben · Nov 16, 2010 · Viewed 155.8k times · Source

I have this string:

"some text\nandsomemore"

I need to remove the "\n" from it. I've tried

"some text\nandsomemore".gsub('\n','')

but it doesn't work. How do I do it? Thanks for reading.

Answer

ocodo picture ocodo · Nov 16, 2010

You need to use "\n" not '\n' in your gsub. The different quote marks behave differently.

Double quotes " allow character expansion and expression interpolation ie. they let you use escaped control chars like \n to represent their true value, in this case, newline, and allow the use of #{expression} so you can weave variables and, well, pretty much any ruby expression you like into the text.

While on the other hand, single quotes ' treat the string literally, so there's no expansion, replacement, interpolation or what have you.

In this particular case, it's better to use either the .delete or .tr String method to delete the newlines.

See here for more info