例如: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________
例如: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________
澤有一個很好的答案。然而,如果你需要刪除所有空白字符(如你貼),你可以使用這個稍微改變正則表達式:
text.gsub(/.\s*$/, "")
您也可以在每個行,砍它:
text.lines.map(&:rstrip).map(&:chop).join($/)
# => The fox is red.
# => The fox is grey.
# => The fox is blue.
# => The fox is green.
請注意,這種方法在結果字符串的末尾缺少換行符。 – toro2k
[rstrip ](http://www.ruby-doc.org/core-2.1.0/String.html#method-i-rstrip)和[chop](http://www.ruby-doc.org/core-2.1 .0/String.html#method-i-chop)會做。 – toro2k