Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove newLines at the beginning and at the end of a Ruby string

Tags:

I need to remove newlines at the beginning and at the end of a string in ruby (some sort of trimming).

But JUST at the beginning and the end... The new lines located in the middle of the string must remain untouched.

Thank you!

like image 639
content01 Avatar asked Aug 23 '11 20:08

content01


People also ask

How do you get rid of the N at the end of a string in Ruby?

You need to use "\n" not '\n' in your gsub.

How do I remove special characters from a string in Ruby?

In Ruby, we can permanently delete characters from a string by using the string. delete method. It returns a new string with the specified characters removed.

Does trim get rid of newlines?

trim method removes any line breaks from the start and end of a string. It handles all line terminator characters (LF, CR, etc). The method also removes any leading or trailing spaces or tabs. The trim() method doesn't change the original string, it returns a new string.

How do you remove carriage returns in Ruby?

chomp is a String class method in Ruby which is used to returns new String with the given record separator removed from the end of str (if present). chomp method will also remove carriage return characters (that is it will remove \n, \r, and \r\n) if $/ has not been changed from the default Ruby record separator, t.


1 Answers

You can use String#strip method.

"\tgoodbye\r\n".strip   #=> "goodbye" 
like image 127
Daniel O'Hara Avatar answered Sep 21 '22 08:09

Daniel O'Hara