Assigning a string by reference / copy?
Can anyone explain the behavior
Scenario 1
str = "hello" str1 = str puts str #=> hello puts str1 #=> hello str1 = "hi" puts str1 #=> hi puts str #=> hello Here, changing the value of str1 does not affect the value of str .
Scenario 2
str = "hello" str1 = str str1.gsub! "hello", "whoa!" puts str1 #=> whoa puts str #=> whoa Does not affect gsub! only str1 ? Why does he change str ? If str1 just contains a reference to str , then why didn't the value change in Script-1 ?
Look carefully:
Scenario 1
str = "hello" str1 = str puts str #=> hello puts str1 #=> hello p str.object_id #=>15852348 p str1.object_id #=> 15852348 In the above case, str and str1 contain a reference to the same object that is confirmed by object_id . Now you use the local variable str1 in the following case to store the new object "hi" , which is also confirmed by two different object_id s.
str1 = "hi" puts str1 #=> hi puts str #=> hello p str.object_id #=> 15852348 p str1.object_id #=> 15852300 Scenario 2
`String # gsub! He speaks:
Replaces String # gsub with a place, returns str or nil if no substitutions were performed. If a block and no replacement are specified, a counter is returned instead.
str = "hello" str1 = str str1.gsub! "hello", "whoa!" puts str1 #=> whoa puts str #=> whoa p str.object_id #=>16245792 p str1.object_id #=>16245792 When assigning a variable, this does not affect whether the variable had the same name, and if so, what value it had. In scenario 1, str is finally assigned str1 = "hi" , and everything that happened to it doesn't matter before that. Scenario-1 is the same as without str1 = str .
str = "hello" str1 = "hi" In script-2, str and str refer to the same line. If you change this with one of the variables pointing to this line, then when you call it through another variable, it refers to the same changed line.