Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String assignment by reference/copy?

Tags:

ruby

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?

like image 487
Mudassir Ali Avatar asked Apr 26 '13 06:04

Mudassir Ali


People also ask

Can we assign one string to another in java?

As we know that String is an immutable object, so we can just assign one string to another for copying it. If the original string value will change, it will not change the value of new String because of immutability.

Does JavaScript pass strings by reference?

In fact, Strings in Javascript are indeed passed “by reference”. Thus, calling a function with a string does not involve copying the string's contents. However, JavaScript Strings are immutable; in contrast to C++ strings, once a JavaScript string has been created it cannot be modified.

What is string assignment?

String assignment is performed using the = operator and copies the actual bytes of the string from the source operand up to and including the null byte to the variable on the left-hand side, which must be of type string. You can create a new variable of type string by assigning it an expression of type string.


1 Answers

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
like image 120
Arup Rakshit Avatar answered Nov 05 '22 12:11

Arup Rakshit