Integers Are Special

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:

object_ids.rb

# 10 and x after each assignment are the same object puts( 10.object_id ) x = 10 puts( x.object_id ) x ...

Get The Book of Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.