Numbers are kind of special as they actually don't exist as real objects in memory. This would be unfeasible as there are infinite many of them.
Instead, Ruby emulates them being objects using certain conventions. i.e. you will notice that the object_id
of a Fixnum
is always 2 * i + 1
(with i
being the number). Using this convention, Ruby can emulate the numbers that are represented as actual plain numbers on the CPU for performance and space constraints to look like objects to your Ruby program.
As Fixnum
s don't actually exist as discrete objects in memory, you can't change them individually. Instead, numbers are considered immutables. They can mostly be used as objects, but you can't change them as they are not actual discrete objects. There are a few other immutable objects in Ruby, e.g. false
, true
, nil
.
In comparison, the string will be handled as a discrete ruby object that can be changed and is not immutable. It thus behaves like the majority of all the other Ruby objects you will encounter.