views:

488

answers:

1

This may be a bit of a nooby question, I have been trying to get better at ruby recently, and started reading the fantastic The Ruby Programming Language. Something that was mentioned is that string literals are considered mutable, so in a loop it is better to use a variable then a literal, as a new string will get instantiated at every iteration.

My question is why? At first I thought it was because of interpolation, but symbols are immutable and they support interpolation. Coming from a static background, it doesn't really make much sense to me.

EDIT:

After reading thenduks answer, I think I may have it. AFAIK, languages like Java or C# don't have destructive string methods (they use upcase, but not upcase!). Because of things like upcase! or <<, the literal cannot be immutable.

Not 100% sure on that, the other possibility is that it is a compile-time interning that happens, which is something that just doesn't happen in a scripting language.

+5  A: 

Not really sure what exactly your question is, but consider the following code:

10.times { puts "abc".object_id }

This prints out 10 different id's. Why? Just because you know this string wont change doesn't mean Ruby does. If you think that "abc" should only be created once then what happens if you do:

10.times { puts "abc".upcase! }

The upcase! method mutates the string to be upper case, on the next iteration the string created in the first iteration isn't the same anymore.

Perhaps post a code example that is confusing to you?

thenduks
added a bit more to the question, and gave a +1 :)
Matt Briggs