Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby string mutability

Tags:

string

ruby

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.

like image 465
Matt Briggs Avatar asked Jan 23 '09 16:01

Matt Briggs


1 Answers

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?

like image 59
rfunduk Avatar answered Nov 02 '22 04:11

rfunduk