How to replace multiple newlines in a row with one newline using Ruby

后端 未结 9 849
陌清茗
陌清茗 2021-02-05 03:42

I have a script written in ruby. I need to remove any duplicate newlines (e.g.)

\\n
\\n
\\n

to

\\n

My current

9条回答
  •  攒了一身酷
    2021-02-05 04:05

    Simply splitting and recombining the lines will give the desired result

    >> "one\ntwo\n\nthree\n".split.join("\n")
    => "one\ntwo\nthree"
    

    Edit: I just noticed this will replace ALL whitespace substrings with newlines, e.g.

    >> "one    two three\n".split.join("\n")
    => "one\ntwo\nthree"
    

    First check that this is what you want!

提交回复
热议问题