2015-07-10 97 views
1

誰能幫我,如何從在紅寶石串的每一行刪除尾隨空格....例如:刪除紅寶石後從每行空格的字符串

str = "Hello everyone. \nHope you guys are doing good \nstrange i can't remove this spaces" 

我試着rstrip,但它不適合我....可能必須嘗試gsub ....我希望答案在下面wayy。

"Hello everyone.\nHope you guys are doing good\nstrange i can't remove this spaces" 
+0

rstrip在字符串的末尾剝離空格,而不是在每行的末尾。你可以使用正則表達式在每個'\ n'之前進行替換。 – jcoppens

回答

3
str.split("\n").map(&:rstrip).join("\n") 

它可能與正則表達式是可行的,但我更喜歡這種方式。

+0

這看起來很貴 – Yule

+0

謝謝DickieBoy – Sheharose

1

您可以使用gsub!,這將改變接收器:使用另外一個gsub

str = "Hello everyone. \nHope you guys are doing good \nstrange i can't remove this spaces" 
str.gsub!(/\s\n/, "\n").inspect 
#=> "Hello everyone.\nHope you guys are doing good \nstrange i can't remove this spaces" 
0

或者這樣

str.each_line.map(&:strip).join("\n") 
#=> "Hello everyone.\nHope you guys are doing good\nstrange i can't remove this spaces" 
0

str.gsub(/\s+$/, '') 
#=> "Hello everyone.\nHope you guys are doing good\nstrange i can't remove this spaces" 

/\s+$/一個或多個空格匹配(\s+)就在之前換行符($