On Fri, Dec 02, 2005 at 07:27:32PM +0900, Ron Jeffries wrote:
[...]
> Specifically, does slicing a String copy the bytes, or point into the old
> string, and similarly for Array? I see that if I modify the slice, the original
> is not modified, and vice versa, but have the bytes already been copied when the
> slice is created? Or not until later?
> 
> Similar questions for Array, all around, and for operations like <<.
>
> Bottom line, are all the methods of String and Array directly allocating
> storage, or are any of them "virtual"?
> 
> My guess is that the bytes are copied. If so, is anyone aware of a class or
> classes that address substrings and such as virtual copies?

Ruby does use COW for arrays and strings, so internal pointers are
reused and the data they point to duplicated when actually needed.

somearray[start, size]  will always reuse the internal array.
If I'm reading rb_str_substr correctly, somestring[start, rsize] will
copy the bytes unless start'+rsize == somestring.size (start' being
the adjusted offset), amongst other conditions.

-- 
Mauricio Fernandez