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"
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"
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!
(\n*) is needlessly complex. There is no need to group \n, nor do you care about the case where there is no new-line so use \n by itself: sub(/\n+$/, '') is all that's needed.*strip methods to actually strip the string?strip.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()
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"
"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$/,'')
/$\n/ would find new-lines after the current line, not new-lines at the end of the current line. Instead, you need /\n$/.