On Jul 22, 10:39 pm, “Michael W. Ryder” [email protected]
wrote:
Re: Is there a replacement for sub?
On 7/20/07, Martin DeMello [email protected] wrote:My solution has been to override these bang! methods to return self
end
p arr => [1, 2, 3, 4, 5, 6]
new sub! method to something like subf! for just that reason. I still
prefer this version much better than the original version as there are
no surprises. It is very hard to change 30+ years of practice overnight.David- Hide quoted text -
Show quoted text – Hide quoted text -
Show quoted text -
Actually you do not have to define subf! as an intermediate step
you can directly define subn and subn! directly
class String
def subn!(pattern, replacement, n = 1)
n.times { self.sub!(pattern, replacement) }
self # or return self
end
def subn(pattern, replacement, n = 1)
return self if n < 1
@str = self.sub(pattern, replacement)
(n-1).times { @str = @str.sub(pattern, replacement) }
@str # or return @str
end
end
Note that sub and sub! are the original definitions
You use subn(pattern, replacement) and subn!(pattern, replacement) as
substitutes for sub(pattern, replacement) and sub!(pattern,
replacement) which eliminate the unpleasant surprises.
In addition, both can be safely chained !!!
Hope this helps