Tuesday, January 18, 2011

Strings in Ruby vs. C#

In Ruby:
s1 = "string"
s2 = s1
s2 << "a"
s1.should == s2

In C#:
string s1 = "string";
string s2 = s1;
s2.Insert( 0, "a" );
Assert.NotEqual( s1, s2 );

Strings in C# are immutable. So trying to change a string actually creates a new string. So updating s2 does not update s1.

Strings in Ruby are mutable. So strings in Ruby act like pointers and s1 is updated when you update s2.

UPDATE 1/19/2011:
To be more clear, here are some more examples of how Ruby behaves:

s1 = "string"
s2 = s1
s2 += "a"
s2.should_not == s1

s1 = "string"
s2 = s1
s2.should == s1


  1. That's really weird. I always concatenate with += in ruby, so I completely missed this. The only other mutation I can even think of is individual character assignment (s2[3] = ?a), but I never actually do that.
    Oh, I guess gsub! is something that would mess me up.
    Thanks for sharing.

  2. This comment has been removed by the author.

  3. This is peculiar "<<" shovel operator behavior in ruby?. Using assignment operator will make the string strings mimic immutability.