如何删除尾随空格,然后删除最后一个字符?

时间:2014-02-10 15:10:38

标签: ruby

例如:The fox is red.x________(将下划线视为空格)。如何删除空格和x?

修改 如果有这样的几行怎么办?

The fox is red.x________
The fox is grey.x________
The fox is blue.x________
The fox is green.x________

3 个答案:

答案 0 :(得分:1)

你也可以越过每一行,然后砍掉它:

text.lines.map(&:rstrip).map(&:chop).join($/)
# => The fox is red.
# => The fox is grey.
# => The fox is blue.
# => The fox is green.

答案 1 :(得分:0)

回答原来的问题:

"The fox is red.x        ".sub(/. *\z/, "")
# => "The fox is red."

更改后的问题答案:

text.gsub(/. *$/, "")

答案 2 :(得分:0)

萨瓦有一个很好的答案。但是,如果你需要删除所有空白字符(如你发布的那样),你可以使用这个稍微修改过的正则表达式:

text.gsub(/.\s*$/, "")