Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why did Matz choose to make Strings mutable by default in Ruby?

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.)

like image 724
Seth Tisue Avatar asked Apr 09 '10 15:04

Seth Tisue


People also ask

Are strings mutable in Ruby?

In most languages, string literals are also immutable, just like numbers and symbols. In Ruby, however, all strings are mutable by default.

What is mutable string in OOP?

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.


1 Answers

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.

like image 55
rjh Avatar answered Oct 07 '22 21:10

rjh