Reputation: 59
I used chomp
to remove multiple "\n"
from a string, but it only removes one. How can I remove multiple "\n"
characters from a string?
My string looks like:
"Ttyyuhhhjhhhh\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
Upvotes: 1
Views: 2718
Reputation: 2221
As you need to strip from the end of your string, use rstrip
str = "Ttyyuhhhjhhhh\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
str.rstrip()
Upvotes: 8
Reputation: 51093
If you really just want to remove newlines, and not other whitespace, strip
and rstrip
(which remove all whitespace) are not the answer. The regex /\n+\Z/
will match any number of newlines at the end of a string:
str1 = "text \t\n\n\n"
# => "text \t\n\n\n"
str1.sub(/\n+\Z/, '')
# => "text \t"
Note that this works (and without the multiline regexp modifier /m
) on multi-line strings as well, leaving newlines in the middle of the string intact:
str2 = str1 + str1 + str1
# => "text \t\n\n\ntext \t\n\n\ntext \t\n\n\n"
str2.sub(/\n+\Z/, '')
# => "text \t\n\n\ntext \t\n\n\ntext \t"
Upvotes: 0
Reputation: 18572
"Ttyyuhhhjhhhh\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n".gsub(/\n$/,'')
Upvotes: -2
Reputation: 12503
The method strip
will take care of removing all leading and trailing white spaces for you.
If you only want to remove the \n
from the end of the string you can use a regexp such as:
string.gsub!(/(\n*)$/, '')
or rstrip!
string.rstrip!
Upvotes: 8