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

前端 未结 8 2146
面向向阳花
面向向阳花 2021-02-18 17:41

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

相关标签:
8条回答
  • 2021-02-18 18:17
    s.sub(/^[\n\r]*/, '')
    

    This removes leading newlines (carriage returns and line feeds, as in chomp), not any whitespace.

    0 讨论(0)
  • 2021-02-18 18:18

    This should work for you: s.strip.

    0 讨论(0)
  • 2021-02-18 18:23

    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
    
    0 讨论(0)
  • 2021-02-18 18:30

    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

    0 讨论(0)
  • 2021-02-18 18:30

    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 \rs and \ns 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.

    0 讨论(0)
  • 2021-02-18 18:33

    A way to do this for whitespace or non-whitespace characters is like this:

    s = "\naaaa\nbbbb"
    s.slice!("\n") # returns "\n" but s also has the first newline removed.
    puts s # shows s has the first newline removed
    
    0 讨论(0)
提交回复
热议问题