开发者

How to remove newLines at the beginning and at the end of a Ruby string

I need to remove newlines at the beginning and开发者_运维知识库 at the end of a string in ruby (some sort of trimming).

But JUST at the beginning and the end... The new lines located in the middle of the string must remain untouched.

Thank you!


You can use String#strip method.

"\tgoodbye\r\n".strip   #=> "goodbye"


String.strip will remove all extra whitespace from the front and back, leaving innards alone.

http://ruby-doc.org/core/classes/String.html#M001189


This should do it:

string.lstrip!.rstrip!


If your intent is to strip just whitespace then the strip method should work...but if your trying to target new lines specifically then maybe try this:

"\r\na b c d\r\ne f g\r\n".gsub(/^\r\n/, "").gsub(/\r\n$/, "")
=> "a b c d\r\ne f g"

the gsub method will use regular expression to target the beginning ^ and end $ locations for replacement with "".

NOTE: Here I made the assumption that your newline is \r\n. This may not be platform independent.


The platform independent version of NPatel's answer is:

"\nabc\ndef\n".gsub(/^#{$/}/, "").gsub(/#{$/}$/, "")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜