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
.