2011-02-07 25 views
1

一個段落所以我編碼紅寶石更改每一個字和我有幾句話:在使用Ruby

The sky above the port was the color of television, tuned to a dead channel. "It's not like I'm using," Case heard someone say, as he shouldered his way through the crowd around the door of the Chat. "It's like my body's developed this massive drug deficiency." It was a Sprawl voice and a Sprawl joke. The Chatsubo was a bar for professional expatriates; you could drink there for a week and never hear two words in Japanese. 

,我需要修改該段的每一個字不改變結構。我最初的想法是分割空白,然後重新加入它,但問題是你得到標點符號。如果你分裂以便你知道這個詞,很難重新加入,因爲你不知道正確的標點符號。

是否有更好的方法來做到這一點比傳統的拆分,地圖,連接組合?或者,也許只是一個很好的拆分正則表達式,所以它很容易重新加入?

+2

我想這取決於你想要做的每一個字的... – 2011-02-07 21:36:49

+0

你想要的判斷有意義嗎?因爲不然的話,你可以分割空白和所有已知的標點符號並替換所有的令牌並重新加入 – 2011-02-07 21:40:34

回答

3

使用GSUB與塊:

str = %q(The sky above the port was the color of television, tuned to a dead channel. 
"It's not like I'm using," Case heard someone say, as he shouldered his way through the crowd 
around the door of the Chat. "It's like my body's developed this massive drug deficiency." 
It was a Sprawl voice and a Sprawl joke. The Chatsubo was a bar for professional expatriates; 
you could drink there for a week and never hear two words in Japanese.) 

puts str.gsub(/\w+/){|word| word.tr('aeiou','uoaei') } 

結果:

Tho sky ubevo tho pert wus tho celer ef tolovasaen, tinod te u doud chunnol. 
"It's net lako I'm isang," Cuso hourd semoeno suy, us ho sheildorod has wuy threigh tho crewd 
ureind tho deer ef tho Chut. "It's lako my bedy's dovolepod thas mussavo drig dofacaoncy." 
It wus u Spruwl veaco und u Spruwl jeko. Tho Chutsibe wus u bur fer prefossaenul oxputrautos; 
yei ceild drank thoro fer u wook und novor hour twe werds an Jupunoso. 

那麼,這#tr方法將工作,沒有正則表達式,但你的想法。

+1

哦,太棒了。完全沒有在文檔中看到gsub。我必須失明。另外,%q非常棒。謝謝! – icco 2011-02-07 23:49:57

3

我會匹配單詞邊界之間詞與正則表達式,以避免影響標點符號或空格,如:

s = "This is a test, ok? Yes, fine!" 
s.gsub!(/\b(\w+)\b/) {|x| "_#{x}_"} 
s = "_This_ _is_ _a_ _test_, _ok_? _Yes_, _fine_!"