Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does variables in Ruby determine whether to hold a new reference?

Tags:

ruby

I learned that in Ruby, variables hold references to objects, not the objects themselves. For example:

a = "Tim"
b = a
a[0] = 'J'

Then a and b both have value "Jim".

However if I change the 3rd line to

a = "Jim"

Then a == Jim and b == Tim

I assume that means the code I changed created a new reference for a.

So why does changing a letter or changing the entire string make so much difference?

Follow-up question: Does Java work the same way?

Thank you.


1 Answers

The single thing to learn here is the difference between assignment and method call.

a = 'Jim'

is an assignment. You create a new string object (literal 'Jim') and assign it to variable a.

On the other side,

a[0] = 'J'

is a method call on an object already referenced by the variable a. A method call can't replace the object referenced by the variable with another one, it can just change the internal state of the object, and/or return another object.

like image 69
Mladen Jablanović Avatar answered Jan 02 '26 02:01

Mladen Jablanović