2012-05-31 22 views
0

比方说,我有这样的一个叫做“道”文件: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. 

而且我想在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),但我不知道如何将单行换行改为双行换行。我怀疑是通过正则表达式,但我不知道从哪里开始。

回答

0

你可以用gsub做到这一点:

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

或就地与gsub!

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

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

+0

我发誓我曾尝试过,但无论如何,这工作完美。谢谢! –

+0

如果你多次运行这个,该怎么办? \ n字符的数量将呈指数增长! –

+0

@MatheusMoreira:是的,有什么令人惊讶的吗? –