Object_id


#1

What is the significance of the object_id in the example below? I read the documentation in Ruby Doc and it said that it returns an integer identifier for obj. Please explain what does it mean by that and how this can be used in a program?

puts "string".object_id
puts "string".object_id

puts :symbol.object_id
puts :symbol.object_id

#2

When creating an object it gets assigned an object id. It’s really just a reference to a location in memory.
This is used internally by the language to do a number of things.

For a programmer you could use it to make sure that you have the exact object you want.
Maybe you meant to only have one object of type Author Douglas_Adams
You can check that you are referring to the Author you intended.

You really won’t be needing to worry about object_id much.


#3

Notice that it is object_id, and not variable_id?

a = "string"
b = a
puts a.object_id
puts b.object_id

a = 42
b = 42
puts a.object_id
puts b.object_id

Output

16484320
16484320
85
85

It’s the object that has an id. When two variables are assigned the same value, they point to the same object, hence, one id, not two. Python is like this, too.


#4

mtf makes an excellent point, this code demonstrates it rather well:

a = ['a', 'b', 'c']
b = a

puts a.object_id
puts b.object_id

b[1] = 'd'
puts a

given a and b are the same object, any changes made to the array will be reflected in both variable.


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.