From: Michael Fellinger Date: 2007-07-26T11:00:27+09:00 Subject: Re: rtrim and ltrim function for ruby: is this ok? On 7/26/07, Ian Whitlock wrote: > Leon Bogaert wrote: > > This works. But I would rather see the first object changed. Is this > > possible? > > I would argue that ltrim and rtrim should not remove one character, but > a sequence of the given character. The following code probably does > not meet all ruby conventions, but it does what you request and it does > reserve ! for its intended purpose. Since we got the power of regex/gsub, let's use it :) class String def rtrim(char) dump.rtrim!(char) end def rtrim!(char) gsub!(/#{Regexp.escape(char)}+$/, '') end def ltrim(char) dump.ltrim!(char) end def ltrim!(char) gsub!(/^#{Regexp.escape(char)}+/, '') end end s = "aaaaaabacbccccc" p s s.rtrim!("c") p s s.ltrim!("b") p s s.ltrim!("a") p s