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

前端 未结 8 2097
面向向阳花
面向向阳花 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:36

    Not sure if it's the best way but you could try:

    s.reverse.chomp.reverse
    

    if you want to leave the trailing newline (if it exists).

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

    To be perfectly accurate chomp not only can delete whitespace, from the end of a string, but can also delete arbitrary characters.

    If the latter functionality is sought, one can use:

    '\naaaa\nbbbb'.delete_prefix( "\n" )
    

    But now you this works for arbitrary characters exactly like chomp.

    0 讨论(0)
提交回复
热议问题