Rpranata Rpranata - 2 months ago 50
Ruby Question

How to print the memory location of a Ruby object

Is there a way to print out the memory location of a Ruby object, not from

puts self
as I want to have a custom
method and print the memory pointer location as one of the pieces of information to be output.


I don't know why would you want such a feature, and this is very implementation-specific, but on MRI 1.9 you can (ab)use object_id:

ruby-1.9.2-p180 :022 > class A; end
 => nil 
ruby-1.9.2-p180 :023 > a = A.new
 => #<A:0xa2b72e4> 
ruby-1.9.2-p180 :024 > a.object_id.to_s(16)
 => "515b972" 
ruby-1.9.2-p180 :025 > (a.object_id << 1).to_s(16)
 => "a2b72e4" 

For an explanation of why does it work, check out the relevant lines in MRI gc.c.

Note that this will not work on other implementations (JRuby, Rubinius), and may very well break in future versions of Ruby. Also, there may be no way at all to get the address in some implementations (I suspect that you cannot in JRuby; I'm not sure, through).