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!
You need to use "\n" not '\n' in your gsub.
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.
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.
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.
You can use String#strip method.
"\tgoodbye\r\n".strip #=> "goodbye"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With