From: Timothy Hunter Date: 2005-06-05T05:20:25+09:00 Subject: Re: Question about string's in-place modification Sam Kong wrote: > Hello! > > I wonder how destructive methods work in the behind. > > For example, > > s = '12345' > s2 = s > s.sub!('3', 'three') > puts s #->'12three45' > puts s2 #->'12three45' > > Destructive methods are in-place. > Does that mean the object doesn't change its location in memory? > Probably not. > I don't think it's possible as the object might need more space and > need to move to a bigger empty space for the changed data. > If it moves, the references pointing to it should be updated as well. > > How exactly does that work? > > Thanks in advance. > Sam > Don't think of an object's id as a memory address. Think of it as a handle for a memory address. That way, if the memory address of an object needs to change (if, for example, Ruby needs to allocate more memory for a string) Ruby can update the id with the new address and the id can remain the same.