2015-07-10 54 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+)就在之前换行符($