It's the reverse of this question: Why can't strings be mutable in Java and .NET?
Was this choice made in Ruby only because operations (appends and such) are efficient on mutable strings, or was there some other reason?
(If it's only efficiency, that would seem peculiar, since the design of Ruby seems otherwise to not put a high premium on faciliating efficient implementation.)
In most languages, string literals are also immutable, just like numbers and symbols. In Ruby, however, all strings are mutable by default.
Therefore mutable strings are those strings whose content can be changed without creating a new object. StringBuffer and StringBuilder are mutable versions of String in java, whereas the java String class is immutable. Immutable objects are those objects whose contents cannot be modified once created.
This is in line with Ruby's design, as you note. Immutable strings are more efficient than mutable strings - less copying, as strings are re-used - but make work harder for the programmer. It is intuitive to see strings as mutable - you can concatenate them together. To deal with this, Java silently translates concatenation (via +
) of two strings into the use of a StringBuffer object, and I'm sure there are other such hacks. Ruby chooses instead to make strings mutable by default at the expense of performance.
Ruby also has a number of destructive methods such as String#upcase!
that rely on strings being mutable.
Another possible reason is that Ruby is inspired by Perl, and Perl happens to use mutable strings.
Ruby has Symbols and frozen Strings, both are immutable. As an added bonus, symbols are guaranteed to be unique per possible string value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With