Object#object_id

obj.object_id -> integer
Returns: Integer · Updated March 13, 2026 · Core Classes
objects identity memory core

Every object in Ruby has a unique integer identifier called its object_id. This value corresponds to the object’s memory address in MRI (the reference implementation). You can use object_id to:

  • Check if two variables reference the same object
  • Implement object caching or memoization
  • Build identity-based data structures

Syntax

object.object_id

There are no parameters—object_id is called on an object instance.

Examples

Basic usage

str = "hello"
str.object_id
# => 70297845295380

# Same string, different object
"hello".object_id
# => 70297845295360

# Different object IDs confirm they're separate objects
str.object_id != "hello".object_id
# => true

Checking object identity

# Using dup creates a new object
original = "hello"
copy = original.dup

original.object_id != copy.object_id
# => true

# Assignment creates a reference to the same object
alias_ref = original

original.object_id == alias_ref.object_id
# => true

Common Patterns

Memoization with object_id

class ExpensiveService
  def initialize
    @cache = {}
  end

  def fetch(key)
    @cache[key] ||= compute(key)
  end

  private

  def compute(key)
    # Simulate expensive computation
    sleep 1
    "result for #{key}"
  end
end

Object identity in collections

# Use object_id as a unique key when objects lack natural IDs
users = []
users << user1 = Struct.new(:name).new("Alice")
users << user2 = Struct.new(:name).new("Bob")

user1.object_id == users[0].object_id
# => true

Special Cases: Symbols and Integers

Unlike most objects, Ruby’s Symbols and Integers are immediates—they are stored directly in the variable, not as references to objects on the heap. This means:

  • Every occurrence of the same Symbol or Integer has the same object_id
  • They are not garbage collected in the same way as regular objects
# Symbols: same symbol = same object_id
:symbol.object_id
# => 1141748

:symbol.object_id
# => 1141748 (same!)

# Integers: small integers are cached
42.object_id
# => 85

42.object_id  
# => 85 (same!)

# Larger integers create new objects
10000.object_id != 10000.object_id
# => true (different objects)

This behavior makes Symbols and Integers particularly efficient when used as hash keys.

Errors

object_id never raises an exception—it works on any object.

See Also