0

I have a string:

str="D\\projects\\myown\\java"

I assigned this string to two variables like:

str1=str
str2=str

After I did the below operation:

idgb1=str1.gsub!("\\","_")

I get str1 as D_projects_myown_java and str2 is the same. why does this happen? I don't want str2 to change its value.

sawa
  • 165,429
  • 45
  • 277
  • 381
ѕтƒ
  • 3,547
  • 10
  • 47
  • 78

2 Answers2

5

str1 and str2 are just references to str, the string is not copied to those variables. And String#gsub! updates the string in place.

If you want to keep str2 intact, you need to do it like this:

str2 = str.dup

or

str2 = str.clone

Besides, if you use String#gsub instead of String#gsub!, str and str2 will not be changed.

Yanhao
  • 5,264
  • 1
  • 22
  • 15
1

for further information you might also want to read up on shallow vs deep copies, here a link to Wikipedia that explains the concept: enter link description here

Also in addition, I wanted to add, that the '!' usually identifies what are called 'bang methods'. These are methods that ultimately alter the state of the variable they're called on.

This link touches upon bang methods and actually has an example which is very similar to the problem you described: enter link description here

Hope this helps

flaky
  • 6,816
  • 4
  • 29
  • 46