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","")
Source: Stackoverflow.com