Ogrish Man Ogrish Man - 2 months ago 9
Ruby Question

In Ruby, what's the easiest way to "chomp" at the start of a string instead of the end?

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. Thanks.

s = "\naaaa\nbbbb"
s.sub!(/^\n?/, "")

Answer

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