Is it possible with Ruby reflection to retrieve all the objects containing a reference to some "var.object_id"?

415 views Asked by At

Suppose in Ruby I have a = "value"; arr1 = [a, b, c]; and arr2 = [a, d, e];

Is there some reflective programming technique allowing me to say:

What are all the objects which have a reference to a.object_id?

and getting as an answer something like:

object_id:123123 (Array)

object_id:234234 (Array)

1

There are 1 answers

4
Aleksei Matiushkin On

There is ObjectSpace, commonly used for this kind of queries. Please note, that the code above will produce a lot of garbage output in IRB/Pry since those introduce their own bindings etc.

#!/usr/bin/env ruby
a = 42 ; b,c,g,h = [nil]*4 ; arr1 = [a,b,c] ; arr2 = [g,h,a]
ObjectSpace.each_object(Array) do |arr|
  puts "#{arr.__id__}: #{arr.inspect}" if arr.include? a
end

#⇒ 12491500: [nil, nil, 42]
#⇒ 12491520: [42, nil, nil]

This code has a side effect: it actually checks whether an array includes a variable by value. That said, plain [42] will be counted as well and you are probably interested in making more sophisticated check inside select.

But generally speaking, the answer to the question “what to use to query the global object space” is that linked in the very beginning of my answer: ObjectSpace.