9

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 has no effect on the value of str.

Scenario-2

str = "hello"
str1 = str
str1.gsub! "hello", "whoa!"
puts str1 #=> whoa
puts str #=> whoa

Shoudn't the gsub! effect only the str1? Why is it changing str? If str1 just holds the reference to str, then why did the value not change in Scenario-1?

sawa
  • 165,429
  • 45
  • 277
  • 381
Mudassir Ali
  • 7,913
  • 4
  • 32
  • 60

2 Answers2

17

Look below 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 holding the reference to the same object which is proved by the object_id. Now you use the local variable str1 in the below case to hold a new object "hi",which is also proved by the two different object_ids.

str1 = "hi"
puts str1 #=> hi
puts str #=> hello
p str.object_id  #=> 15852348
p str1.object_id #=> 15852300

Scenario-2

`String#gsub! says:

Performs the substitutions of String#gsub in place, returning str, or nil if no substitutions were performed. If no block and no replacement is given, an enumerator 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
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
  • Does this hold true for everything? Everything is an object and everything is assign by reference? Including other things that are normally primitives in other languages such as integers or floats? – Daniel Bingham Nov 14 '14 at 19:04
0

In variable assignment, it has no effect whether there was a variable with the same name, and if so, what value it was. In scenario-1, str is finally assigned str1 = "hi", and whatever happened to it before that is irrelevant. Scenario-1 is the same as the following without str1 = str.

str = "hello"
str1 = "hi"

In Scenario-2, str and str are referring to the same string. If you change that via one of the variables pointing to that string, then when you call it via the other variable, it refers to the same changed string.

sawa
  • 165,429
  • 45
  • 277
  • 381