On Sat, Dec 22, 2012 at 5:15 PM, Paul Magnussen <lists / ruby-forum.com> wrote:
> Hi,
>
> I have programmed in various languages previously, but am new to Ruby.
>
> So far am very impressed with it; but there is one behaviour I find
> quite alarming, which stems from the fact that Ruby treats strings as
> objects rather than as primitives.
>
> For instance:
>
> # a) Number
>
> myNum1 = 5
> myNum2 = myNum1
>
> myNum2 = 3
>
> => myNum1 = 5
> => myNum2 = 3
>
> which is what I would expect.  However,
>
> # b) String
>
> myString3 = "Fred Nerk"
> myString4 = myString3
>
> myString4[0,4] = "Bert"
>
> => myString3 = "Bert Nerk"
> => myString4 = "Bert Nerk"
>
> myString3 has been "corrupted", presumably because setting myString4 to
> it actually set myString4's pointer, not its value, in the standard OO
> fashion.

In Ruby parlance, it's a reference; but essentially correct.

>
> But
>
> # c) String literal
>
> myString1 = "Fred Bloggs"
> myString2 = myString1
>
> myString2[0,4] = "Bert"
>
> puts "Fred Bloggs = " + "Fred Bloggs"
> puts "myString2 = " + myString2
>
> (Output)
>
> => Fred Bloggs = Fred Bloggs
> => myString2 = Bert Bloggs
>
> Has the "Fred Bloggs" literal not been corrupted?  Or did puts just use
> another (uncorrupted) instance of it?

A literal can't be changed. Conceptually at least, every time you have "Fred
Bloggs" in quotes, you're referring to a different object.

>
> So let's make the first string a constant.  That produces the expected
> behaviour in this case:
>
> # d) String constant 1
>
> MyString5 = "Fred Potts"
> MyString5 = "John Potts"
>
> => warning: already initialized constant MyString5
>
> but not in this one:  the constant gets "corrupted".
>
> # e) String constant 2
>
> MyString6 = "Fred Winterbotham"
> myString7 = MyString6
>
> myString7[0,4] = "Bert"
>
> => MyString6 = "Bert Winterbotham"
> => myString7 = "Bert Winterbotham"

Yes. Note that a "constant" in Ruby is something that will trigger a warning
if it's modified, but it's still possible to modify it. A reference to a
constant works the same as a reference to a non-constant object.

>
> So how to get around this?  The following appears to do it:
>
> # f) String constant 3
>
> MyString8 = "Fred Shufflebotham"
> myString9 = MyString8.clone
>
> myString9[0,4] = "Bert"
>
> => MyString8 = "Fred Shufflebotham"
> => myString9 = "Bert Shufflebotham"
>
> but doesn't it cause a memory leak?

Well, the memory used by those objects will stay allocated as long as the
garbage collector can reach them somehow, i.e. there are variables that point
to them or they belong to a collection like an array or hash.

>
> Sorry if this question is too elementary.
>
> --
> Posted via http://www.ruby-forum.com/.
>