W
Warren Brown
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(/(^_+)|(_+$)/,'')
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
def new_rstrip(str = nil)
return self.rstrip if str.nil?
self.sub(/#{str}+$/,'')
end
def new_strip(str = nil)
return self.lstrip if str.nil?
self.gsub(/(^#{str}+)|(#{str}+$)/,'')
end
end
If there is an interest in this, I can provide patches for 1.6.8 and/or
the latest 1.8 snapshot.
- Warren Brown
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(/(^_+)|(_+$)/,'')
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
def new_rstrip(str = nil)
return self.rstrip if str.nil?
self.sub(/#{str}+$/,'')
end
def new_strip(str = nil)
return self.lstrip if str.nil?
self.gsub(/(^#{str}+)|(#{str}+$)/,'')
end
end
If there is an interest in this, I can provide patches for 1.6.8 and/or
the latest 1.8 snapshot.
- Warren Brown