Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print the memory location of a Ruby object

Tags:

ruby

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 to_s method and print the memory pointer location as one of the pieces of information to be output.

like image 478
Rpranata Avatar asked Aug 07 '11 16:08

Rpranata


1 Answers

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).

like image 72
whitequark Avatar answered Nov 07 '22 13:11

whitequark