From: Paul Magnussen Date: 2012-12-23T08:15:58+09:00 Subject: POLS and string-handling 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. 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? 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" 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? Sorry if this question is too elementary. -- Posted via http://www.ruby-forum.com/.