From: Robert Klemme Date: 2003-07-22T14:29:03+09:00 Subject: Re: Should String#strip take a parameter? "Warren Brown" schrieb im Newsbeitrag news:000201c34fd3$22b24cb0$6449c4d1@warrenpc... > All, > > Several times I have run across the need to strip characters other than > whitespaces from the beginning and/or end of a string. I have always > accomplished this using String#sub (or String#gsub) and an appropriate > pattern. For example: > > price = field.sub(/^0+/,'') > descr = field.gsub(/(^_+)|(_+$)/,'') .... which is not too bad, isn't it? > It occurs to me that this would be a natural extension to the > String#strip methods (1.8 now includes String#lstrip and String#rstrip as > well as the "!" variations) by adding an optional String parameter to them. > The default value of the parameter would be nil to preserve backwards > compatibility, but if the parameter was not nil, the functions would strip > that string (or the string returned by that object's to_str method). > > Example behavior: > > class String > > def new_lstrip(str = nil) > return self.lstrip if str.nil? > self.sub(/^#{str}+/,'') > end If you want to exactly match str you should use Regexp.quote for the argument. Otherwise I'd use a regexp directly and match it at the beginning and at the end. Maybe like this: class String SPACES = /\s+/o def new_strip!(rx=SPACES) gsub!(rx) {|m| $`==""||$'=="" ? nil : m} end def new_strip(rx=SPACES) s=dup; s.new_strip! rx; s end def new_lstrip!(rx=SPACES) gsub!(rx) {|m| $`=="" ? nil : m} end def new_lstrip(rx=SPACES) s=dup; s.new_lstrip! rx; s end def new_rstrip!(rx=SPACES) gsub!(rx) {|m| $'=="" ? nil : m} end def new_rstrip(rx=SPACES) s=dup; s.new_rstrip! rx; s end end Regards Robert