从ruby中的字符串中的每一行中删除尾随空格

时间:2015-07-10 16:03:54

标签: ruby string

任何人都可以帮助我,如何删除ruby中字符串中每行的尾随空格....例如:

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

我试过rstrip,但它不适合我....可能要尝试gsub ....我希望答案是在下面的方式。

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

4 个答案:

答案 0 :(得分:4)

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

它可能与正则表达式有关,但我更喜欢这种方式。

答案 1 :(得分:1)

您可以使用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"

答案 2 :(得分:1)

使用gsub的另一个人:

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

/\s+$/在换行符之前匹配一个或多个空格(\s+)($

答案 3 :(得分:0)

或者像这样

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