Object address in Ruby

debugging, inspect, memory-address, ruby

Solution

You can get the address using object_id and multiplying it by 2* and display it in hex using `sprintf` (aka `%`):

"#<Thing:0x%08x>" % (object_id * 2)

Of course, as long as you only need the number to be unique and don't care that it's the actual address, you can just leave out the `* 2`.

* For reasons that you don't need to understand (meaning: I don't understand them), `object_id` returns half the object's memory address, so you need to multiply by 2 to get the actual address.

Problem

Short version: The default `inspect` method for a class displays the object's address.* How can I do this in a custom `inspect` method of my own? *(To be clear, I want the 8-digit hex number you would normally get from `inspect`. I don't care about the actual memory address. I'm just calling it a memory address because it looks like one. I know Ruby is memory-safe.) Long version: I have two classes, `Thing` and `ThingList`. `ThingList` is a subclass of `Array` specifically designed to hold Things. Due to the nature of Things and the way they are used in my program, Things have an instance variable `@container` that points back to the `ThingList` that holds the `Thing`. It is possible for two Things to have exactly the same data. Therefore, when I'm debugging the application, the only way I can reliably differentiate between two Things is to use `inspect`, which displays their address. When I `inspect` a `Thing`, however, I get pages upon pages of output because `inspect` will recursively inspect `@container`, causing every Thing in the list to be inspected as well! All I need is the first part of that output. How can I write a custom `inspect` method on `Thing` that will just display this? ``` #<Thing:0xb7727704> ``` EDIT: I just realized that the default `to_s` does exactly this. I didn't notice this earlier because I have a custom `to_s` that provides human-readable details about the object. Assume that I cannot use `to_s`, and that I must write a custom `inspect`.

Original source