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.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.