From: Mark Hubbart Date: 2004-09-09T18:35:35+09:00 Subject: Re: Q: Should String.upcase! work on a segment of a string? On Sep 8, 2004, at 5:35 PM, Mike Hall wrote: > Question: Should String.upcase! work on a segment of a string? > > We can assign to a sub-string, so I thought that a bang-method might > also work on a sub-string. > > s = 'AA11zz' # define a string > >> s[4..5].upcase! # try to change part of it > => "ZZ" # yeah, ok, the new string is changed, > but... > >> s > => "AA11zz" # the original string wasn't affected > >> s[4..5] = s[4..5].upcase # so, do it by-hand > => "ZZ" > >> s # and it's ok > => "AA11ZZ" > > Are there edge cases where this wouldn't be appropriate? A string and it's substrings (as accessed by [] and slice) are not related. When you create a substring by taking a slice, it returns a copy of that section of data. Still, this was one of the conveniences I missed from PHP. Here's an idea I've played around with a few times (dirty hack follows): class SubString def initialize(string, range) @string, @range = string, range end def upcase! @string[@range] = @string[@range].upcase end # [...] end class String def sub_str(range) SubString.new(self, range) end end foo.sub_str(2..4).upcase! ==>"STI" foo ==>"teSTIng foo testing" foo.sub_str(/foo/).upcase! ==>"FOO" foo ==>"teSTIng FOO testing" cheers, Mark