Ruby - 如何将单个换行符更改为双换行符?

时间:2012-05-31 11:08:03

标签: ruby regex

假设我在一个名为“tao”的文件中有这个:

If you can talk about it, it ain't Tao. If it has a name, it's just another thing.  
Tao doesn't have a name. Names are for ordinary things.

我想用ruby打开它,然后把它改成:

If you can talk about it, it ain't Tao. If it has a name, it's just another thing.
  
Tao doesn't have a name. Names are for ordinary things.

我知道如何读取文件,并将内容转换为字符串(让我们称之为tao_string),但我不知道如何将单行中断更改为双行中断。我怀疑通过正则表达式,但我不知道从哪里开始。

1 个答案:

答案 0 :(得分:0)

您可以使用gsub执行此操作:

tao_string2 = tao_string.gsub("\n", "\n\n")

或就地gsub!

tao_string.gsub!("\n", "\n\n")

这将通过双换行替换字符串中的所有换行符。