gargvipan
gargvipan

Reputation: 59

How to remove multiple \n from end of string in Ruby

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

Answers (4)

Kamil Šrot
Kamil Šrot

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

David Moles
David Moles

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

Teddy
Teddy

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

Pablo Fernandez heelhook
Pablo Fernandez heelhook

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

Related Questions