Ruby - Integers Object Id

Introduction

In Ruby, an integer or Fixnum has a fixed identity.

Every instance of the number 10 or every variable to which the value 10 is assigned will have the same object_id.

The same cannot be said of other data types.

Each instance of a floating-point number such as 10.5 or of a string such as "hello world" will be a different object with a unique object_id.

Be aware that when you assign an integer to a variable, that variable will have the object_id of the integer itself.

But when you assign some other type of data to a variable, a new object will be created even if the data itself is the same at each assignment:

Demo

# 10 and x after each assignment are the same object
puts( 10.object_id )#   w w  w.j  av a  2s .  c om
x = 10
puts( x.object_id )
x = 10
puts( x.object_id )

# 10.5 and x after each assignment are 3 different objects!
puts( 10.5.object_id )
x = 10.5
puts( x.object_id )
x = 10.5
puts( x.object_id )

Result

Related Topic