0
irb> class A; end
=> nil
irb> a=A.new
=> "#<A:0x3094638>"
irb> a.inspect
=> "#<A:0x3094638>"
irb> b=[]
=> []
irb> b.inspect
=> "[]"

How to get memory address of an array object?

1 Answer 1

5

Use the method Object#object_id.

Returns an integer identifier for obj. The same number will be returned on all calls to id for a given object, and no two active objects will share an id. #object_id is a different concept from the :name notation, which returns the symbol id of name.

Example :-

Arup-iMac:arup_ruby $ irb
2.1.2 :001 > s = "I am a string"
 => "I am a string" 
2.1.2 :002 > obj_id = s.object_id
 => 2156122060 
2.1.2 :003 > ObjectSpace._id2ref obj_id
 => "I am a string" 
2.1.2 :004 > 
Sign up to request clarification or add additional context in comments.

6 Comments

If object_id differ could I say for sure that there are two different objects? And if these ids are the same is this the same object?
@Paul Yes.. You should.
Not necessarily a memory address, though. In particular, it won't be a memory address for 3, :foo, nil, false... (although it still will be unique). But for most objects, it will be a pointer, at least on MRI. Fun fact: for small integers n, object_id should be n * 2 + 1. -1.object_id == -1! :)
@Amadan Humm.. True...True. object_id is enough to get the object address and the same address can be used to get the object back. :-)
I have @channels array in a class. The class should be instantiated once, but when I call the instance from one thread @channels.length is 1 and from other thread = 0. object_id is the same. Array is created and filled only during object's initialization. What could go on?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.