This post will cover the differences between immutability and mutability in Ruby.
An object has state which is often referred to as a value. When a variable is assigned to an object it has a reference to that object. Ex:
This means the variable
a has a reference to the String object with the value “hello world”.
#object_id is a method that Ruby provides and it tells us what the id of the object it is refering to. In this example
a is pointing to the string object with the id 70113614077220.
There are two types of objects - those that are immutable and those that are mutable
These are objects whose state cannot be changed. In Ruby, the Integers class is immutable. Here’s an example
When we assign
number to the value 5 the object id is 11. But when we change
number to the value of 12 the object id is 25. So number is referring to a different object after being reassigned.
Internally it looks like this
Even something like this will cause
number to have a different reference point
Even when we are incrementing
number it actually references a new integer (7) which is a different instance of the Integer class.
These are objects whose state can be changed. In Ruby, Strings, Hashes, and Arrays are a few of the classes that are mutable. Here’s an example
Here’s what’s happening internally
a has a reference to an instance of Hash and each key of the hash is pointing to an instance of String with the corresponding hash value.
Because a Hash is mutable if we add another key, value pair to the hash,
a will have the same reference point (the same object id).
Again here’s what’s happening internally
Subscribe via RSS