Praveen Dhawan
Praveen Dhawan

Reputation: 300

Can we access the objects we created in ruby using their object _ids in ruby?

How are the object IDs assigned in Ruby? Do some objects have fixed object_id? Can we access them using their object _ids?

Upvotes: 1

Views: 407

Answers (2)

Jörg W Mittag
Jörg W Mittag

Reputation: 369438

How are the object IDs assigned in Ruby?

The Ruby Language Specification doesn't say anything about how IDs are assigned, only that

  • an object has to have the same ID over its lifetime
  • no two objects can have the same ID at the same time

Note that this doesn't prohibit that two different objects may have the same ID at different times, i.e. it is allowed to reuse IDs.

Do some objects have fixed object_id?

The Ruby Language Specification doesn't say anything about how IDs are assigned. On some Ruby Implementations some objects may or may not have fixed IDs.

Can we access them using their object _ids?

On some implementations, there is a method called ObjectSpace::_id2ref, but this method is not guaranteed to exist on all implementations, and it may be really expensive and on some implementations must be explicitly enabled with a command line switch.

Upvotes: 1

cremno
cremno

Reputation: 4927

How an object ID is “assigned” depends on the Ruby implementation and other factors like the OS bitness. For example, in CRuby nil.object_id returns 4 on 32-bit and 8 on 64-bit.

Additionally nil is a so called immediate value. true, false, fixnums (small integers) and sometimes even floats are other immediate values. They have fixed IDs for the following reasons:

  • they're passed by value and not by reference like the other (dynamically allocated) objects
  • there's only one nil, one true, one 19, etc. however there can be two different arrays

See the documentation of BasicObject#object_id. You can also click to toggle the source to get a look at the CRuby implementation.

Call ObjectSpace._id2ref to retrieve an object by ID:

id = nil.object_id
ObjectSpace._id2ref(id) # => nil

In some implementations that method may not be implemented or really slow. According to matz it was originally a hack needed to implement weakref but current versions don't call it anymore.

Upvotes: 4

Related Questions