Suppose I have this simple code:
a = 1
b = 1
Does ruby ensure only one instance of numbers by tracking the numbers (so a
and b
would refer to the same object in memory) or just preventing users from creating numbers through the method new
and duplicating/cloning them?
a = 1
b = 1
Both a
and b
refer to the same object.
p a.object_id
=> 3
p b.object_id
=> 3
So when you're comparing a
and b
Ruby compares the object ids (as it does with symbols) which makes comparison performant.
The object_id's of integers, interestingly enough, are always odd. Everything else has even object ids.
Note the comment from Holger Just below which goes into some detail regarding large integers.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments