As I understand its because of the memory usage.
When you initialize object, Ruby will first initialize object in the memory. Then, the variable points to that memory address. When you assign this variable to another one, that one will point to that address also
For example,
a = []
a.object_id # 70220203482480
b = a
b.object_id # 70220203482480
When you add new element, it means, you add the value to the array which initialized in memory, calling a
and b
will both show that array with new element.
a.push(1)
b # [1]
Let see the second example
c = 'reference'
d = c
c.object_id #70220203442960
d.object_id #70220203442960
c.capitalize! # 'Reference'
d # 'Reference'
If you assign d = 'new object'
, Ruby will create another object in the memory and give it value as string new object
, and then, d
will point to that new memory address
d = 'new object'
d.object_id # 70220203334840 (different one)
c # 'Reference' (cause c still point to the last object in memory)