In Ruby, what's the easiest way to "chomp" at the start of a string instead of the end?
lstrip
seems to be what you want (assuming trailing white space should be kept):
>> s = "\naaaa\nbbbb" #=> "\naaaa\nbbbb"
>> s.lstrip #=> "aaaa\nbbbb"
From the docs:
Returns a copy of str with leading whitespace removed. See also String#rstrip and String#strip.
http://ruby-doc.org/core-1.9.3/String.html#method-i-lstrip
strip
will remove all trailing whitespace
s = "\naaaa\nbbbb"
s.strip!
Little hack to chomp leading whitespace:
str = "\nmy string"
chomped_str = str.reverse.chomp.reverse
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.