2010-01-12 64 views

回答

1

在ObjectSpace中也许四处可以帮助:

#!/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>> 
相关问题