Skip to content
Tags

, ,

see and learn – replacing characters using index

October 18, 2011

When you replace characters of a string using index, it does not create a new string internally (if it is copied form another string). so it can end up changing the value of all both the strings:

ruby-1.9.2-p290 :039 > a = "test"
 => "test"
ruby-1.9.2-p290 :040 > b = a
 => "test"
ruby-1.9.2-p290 :041 > b = "new"
 => "new"
ruby-1.9.2-p290 :042 > b
 => "new"
ruby-1.9.2-p290 :043 > a
 => "test"
ruby-1.9.2-p290 :044 > a = "test"
 => "test"
ruby-1.9.2-p290 :045 > b = a
 => "test"
ruby-1.9.2-p290 :046 > a = "new"
 => "new"
ruby-1.9.2-p290 :047 > a
 => "new"
ruby-1.9.2-p290 :048 > b
 => "test"
ruby-1.9.2-p290 :049 > a = "test"
 => "test"
ruby-1.9.2-p290 :050 > b = a
 => "test"
ruby-1.9.2-p290 :051 > b[0] = "r"
 => "r"
ruby-1.9.2-p290 :052 > b
 => "rest"
ruby-1.9.2-p290 :053 > a
 => "rest"

Instead you can try doing this:

ruby-1.9.2-p290 :076 > a = 'test'
 => "test" 
ruby-1.9.2-p290 :077 > b = String.new(a)
 => "test" 
ruby-1.9.2-p290 :078 > b[0] = 'r'
 => "r" 
ruby-1.9.2-p290 :079 > b
 => "rest" 
ruby-1.9.2-p290 :080 > a
 => "test"
Advertisements

From → Uncategorized

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: