Ruby已经初始化了查找对象实例

时间:2014-03-23 01:33:48

标签: ruby

我有以下Ruby程序。

class A    
end

class B
  def method_b
    #find initialized instances of A
  end
end

a = A.new
b = B.new
b.method_b

我可以在method_b中找到已初始化的A实例。当然,我同意如果我可以将变量a作为B.new(a)传递给B类,则可以轻松完成。但是我想在更复杂的环境中应用它,我需要避免多次传递a

1 个答案:

答案 0 :(得分:1)

您可以使用ObjectSpace模块

执行此操作
ObjectSpace.each_object(A).count #count of the number of objects initialized for A
ObjectSpace.each_object(A).to_a #returns you the objects that are already initialized for A

您可以找到ObjectSpace模块here

的文档
class B
  def method_b
    ObjectSpace.each_object(A).to_a
  end
end
相关问题