tags:

views:

57

answers:

2

If I have two objects, one being referenced in another. Then in the first object can I write a method which will give me which other objects it is being referenced in?

+2  A: 

I am not sure how to do it out of the box, but maybe the following post might help you:

What is a ruby object? (introducing Memprof.dump)

Petros
+1  A: 

Perhaps digging around in ObjectSpace could help:

#!/usr/bin/ruby1.8

include ObjectSpace

def print_references_to_foos
  for klass in [Bar, Baz]
    each_object(klass) do |o|
      s = o.inspect
      puts s if s =~ /#<Foo/
    end
  end
end

class Foo
end

class Bar
  def initialize(foo)
    @foo = foo
  end
end

class Baz < Bar
end

foo1 = Foo.new
foo2 = Foo.new
foo3 = Foo.new
bar1 = Bar.new(foo1)
bar2 = Bar.new(foo1)
bar3 = Baz.new(foo2)

print_references_to_foos
# => #<Baz:0xb7e09158 @foo=#<Foo:0xb7e091a8>>
# => #<Bar:0xb7e0916c @foo=#<Foo:0xb7e091d0>>
# => #<Bar:0xb7e09180 @foo=#<Foo:0xb7e091d0>>
# => #<Baz:0xb7e09158 @foo=#<Foo:0xb7e091a8>>
Wayne Conrad