1

please help find some article of the next behavior.

a = 'qwer'
a = b
b << 'ty'
puts b # => 'qwerty'
puts a # => 'qwerty'

but if

a = 'qwer'
a = b
b = 'ty'
puts b # => 'ty'
puts a # => 'qwer'

I know why in this case

I know that it works well, but I can not find an explanation - why so

P.S.

if applicable - please give the links to the articles on this subject (or similar Maybe i miss more interesting feature like this).

Thn.

1

1 Answer 1

5

When you do

a = b

you make variable a keep reference to the same object as variable b. That's why when you type:

b << 'ty'

string contained in variable a will also change - this is the same String instance.

On the other hand, let's say you have variable b containing reference to string 'qwer'. If you have:

a = b
b = 'ty'

in first line you assign variable a to the same object as b. In the second line, you assign a new String object to variable b. So in the end both variables have references to different objects.

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

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.