From: Markus Date: 2004-09-10T04:54:52+09:00 Subject: Re: Q: Should String.upcase! work on a segment of a string? On Thu, 2004-09-09 at 12:40, Mike Hall wrote: > Gavin Sinclair wrote: > > > >> 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 is one object; s[4..5] is another. What you do to the second object is > >none of the first's business. > > I don't understand that... we can outright assign to the substring and it _does_ affect the original string. > > I agree that pulling out s[4..5] (using it on the RHS) will give me a new object, that's cool. > > But -- if the string range reference is on the LHS, then it refers to a segment of 's', not some new object. That's what I'm after. If s.upcase! affects s, then it would be cool if s[4..5].upcase! also affected (a portion) of s. > > But it doesn't, and I guess it won't. > OK. Thanks, everyone! > DON'T TRY THIS TRICK AT HOME It is possible to do what you are asking, but I seriously doubt it is worth the trouble. A sketch (NOT a complete or robust implementation): class String alias at [] def [](arg) case arg when Range then A_magic_substring.new(self,arg) else at(arg) end end end class A_magic_substring attr_reader :host,:loc def initialize(h,l) @host = h @loc = l end def upcase! @host[@loc] = @host.at(@loc).upcase end def to_str @host.at(@loc) end def to_s to_str end def inspect to_str end end s = "My string" p s p s[3..5] s[3..5].upcase! p s