In Ruby, sometimes I need to remove the new line character at the beginning of a string. Currently what I did is like the following. I want to know the best way to do this. Than
So, just for a bit of clarification, there are three ways that you can go about this: sub
, reverse.chomp.reverse
and lstrip
.
I'd recommend against sub
because it's a bit less readable, but also because of how it works: by creating a new string that inherits from your old string. Plus you need a regular expression for something that's fairly simple.
So then you're down to reverse.chomp.reverse
and lstrip
. Most likely, you want lstrip
because it's a bit faster, but keep in mind that the strip
operations are not the same as the chomp
operations. strip
will remove all leading newlines and whitespace:
"\n aaa\nbbb".reverse.chomp.reverse # => " aaa\nbbb"
"\n aaa\nbbb".lstrip # => "aaa\nbbb"
If you want to make sure you only remove one character and that it's definitely a newline, use the reverse.chomp.reverse
solution. If you consider all leading newlines and whitespace garbage, go with lstrip
.
The one case I can think of for using regular expressions would be if you have an unknown number of \r
s and \n
s at the beginning and want to trim them all but avoid touching any whitespace. You could use a loop and the more String methods for trimming but it would just be uglier. The performance implications don't really matter that much.