Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?/, "")
like image 282
Just a learner Avatar asked Feb 11 '12 08:02

Just a learner


People also ask

What is the chomp method 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 removes 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.

How do you get the first character of a string in Ruby?

In Ruby, we can use the built-in chr method to access the first character of a string. Similarly, we can also use the subscript syntax [0] to get the first character of a string. The above syntax extracts the character from the index position 0 .

How do you get the first 3 characters of a string in Ruby?

To access the first n characters of a string in ruby, we can use the square brackets syntax [] by passing the start index and length. In the example above, we have passed the [0, 3] to it. so it starts the extraction at index position 0 , and extracts before the position 3 .

How do you strip a string in Ruby?

Ruby has lstrip and rstrip methods which can be used to remove leading and trailing whitespaces respectively from a string. Ruby also has strip method which is a combination of lstrip and rstrip and can be used to remove both, leading and trailing whitespaces, from a string.


2 Answers

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

like image 139
Michael Kohl Avatar answered Oct 12 '22 01:10

Michael Kohl


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
like image 34
fl00r Avatar answered Oct 12 '22 01:10

fl00r