2012-05-31 36 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:是的,有什麼令人驚訝的嗎? –