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.
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.
tr is a better choice for this task, but as I say, I thought it better to point out the difference in single, double quotes when I answered..delete or .tr ?.gsub because they do less (.delete would very likely be fastest, although a performance profiling would be good to 100% confirm this.)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.
strip only removes leading and trailing whitespace: ruby-doc.org/core-1.9.3/String.html#method-i-strip-21When 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.
delete is not destructive as indicated here. It returns a new string.You don't need a regex for this. Use tr:
"some text\nandsomemore".tr("\n","")
replace just changes the string to a new one, like variable assignment; whereas tr is a character-by-character global find and replace.use chomp or strip functions from Ruby:
"abcd\n".chomp => "abcd"
"abcd\n".strip => "abcd"
strip only removes leading and trailing whitespace - ruby-doc.org/core-1.9.3/String.html#method-i-strip-21#squish will remove all spacing including newlines and tabs.
"some text\nandsomemore".squish #=> "some textandsomemore"
"some text\nand\n\n\n\n\some \t\tmore".squish #=> "some textandsomemore"
"some text andsomemore" in the first case, and "some text and ome more" in the second (the \s at the start of "some" is a whitespace character)for some reason none of those answer works in my case, I figured out my own solution:
3.1.2 :003 > "some text\nandsomemore".split.join(' ')
=> "some text andsomemore"
sometextandsomemore, so not at all what is being asked here.