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

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.

This question is related to ruby regex

The answer is


If you want or don't mind having all the leading and trailing whitespace from your string removed you can use the strip method.

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

as mentioned here.

edit The original title for this question was different. My answer is for the original question.


use chomp or strip functions from Ruby:

"abcd\n".chomp => "abcd"
"abcd\n".strip => "abcd"


When you want to remove a string, rather than replace it you can use String#delete (or its mutator equivalent String#delete!), e.g.:

x = "foo\nfoo"
x.delete!("\n")

x now equals "foofoo"

In this specific case String#delete is more readable than gsub since you are not actually replacing the string with anything.


You don't need a regex for this. Use tr:

"some text\nandsomemore".tr("\n","")