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.
B7f7698eb09ca0849906c023fe6206d3?d=identicon&s=25 Bob Smyph (bobsmyph)
on 2008-10-14 20: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
Beb77c4602c3cac7a12149431366ed11?d=identicon&s=25 The Higgs bozo (higgsbozo)
on 2008-10-14 20:49
Bob Smyph 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"
28f5a897a255c1d9780ad525f0b934a9?d=identicon&s=25 Lyle Johnson (Guest)
on 2008-10-14 20:53
(Received via mailing list)
On Tue, Oct 14, 2008 at 1:46 PM, Bob Smyph
<eric.ramsey@cbc-companies.com> 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. ;)
Aaa2b1f12b65d33422e8cdc48d70c0f9?d=identicon&s=25 Stephen Ball (Guest)
on 2008-10-14 20: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 Smyph
B7f7698eb09ca0849906c023fe6206d3?d=identicon&s=25 Bob Smyph (bobsmyph)
on 2008-10-14 20:57
Thank you all for your fast help.
This topic is locked and can not be replied to.