Forum: Ruby Remove only TRAILING whitespace

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Bob S. (Guest)
on 2008-10-14 22:46
Is there any way to only remove trailing white space from a string. I
have tried to use strip but that will also take off leading white space
and I want to keep that.

any help is appreciated
The H. (Guest)
on 2008-10-14 22:49
Bob S. wrote:
> Is there any way to only remove trailing white space from a string. I
> have tried to use strip but that will also take off leading white space
> and I want to keep that.
>
> any help is appreciated

irb(main):001:0> "sldkfj       ".sub(/\s+\Z/, "")
=> "sldkfj"
Lyle J. (Guest)
on 2008-10-14 22:53
(Received via mailing list)
On Tue, Oct 14, 2008 at 1:46 PM, Bob S.
<removed_email_address@domain.invalid> wrote:

> Is there any way to only remove trailing white space from a string. I
> have tried to use strip but that will also take off leading white space
> and I want to keep that.

String#rstrip will remove just the white space on the end (the "right"
side) of the string. Likewise, String#lstrip removes leading white
space only. And you already know about String#strip. ;)
Stephen B. (Guest)
on 2008-10-14 22:55
(Received via mailing list)
str = "  string  "

rightTrim = str.rstrip
=> "   string"

# for completeness
leftTrim = str.lstrip
=> "string   "

On Tue, 14 Oct 2008 14:46:43 -0400, Bob S.
Bob S. (Guest)
on 2008-10-14 22:57
Thank you all for your fast help.
This topic is locked and can not be replied to.