Variable References and Mutability of Objects [notes]

https://launchschool.com/blog/references-and-mutability-in-ruby

Variables

x = 'anthony'
x.object_id => 4502360

The variable x references a String object which has the value "anthony”. Another way of saying it is, a String object with the value "anthony"has been assigned to the variable x. This is achieved by storing the object id of the String Object.

x = 'anthony'
y = x
x.object_id => 4502360
y.object_id => 4502360

x has been assigned to y so that both variables reference the same String object. x and y are said to be aliases for each other.

x = 'anthony'
y = x
x.object_id => 4502360
y.object_id => 4502360
x = 'hinchliff'
x.object_id => 20066620
y.object_id => 4502360

x has been resigned and now references a different String object.

Mutability

x = 1
x.object_id => 3
x += 1
x.object_id => 5

The int object initially referenced by x was not modified += as numbers are immutable; instead x was reassigned to a new Int object. Every time a mutation is attempted on a immutable object a new object is created.

x = ["a", "b", "c"]
x.object_id => 16604760
x[-1]= 'd' => ["d", "b", "c", "d"]
x.object_id => 16604760

The Array object referenced by x was mutated and therefore x was not reassigned to a new object. (however, the element at x[0] was reassigned to a new String object).

Show your support

Clapping shows how much you appreciated Anthony Hinchliff’s story.