如何在 Ruby 中查找类的每个实例 [英] How to find each instance of a class in Ruby

查看:29
本文介绍了如何在 Ruby 中查找类的每个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 Ruby 中获取某个类的所有对象?

Is there a way to get all the objects that are of a certain class in Ruby?

澄清:

class Pokemon
end

pikatchu = Pokemon.new
charmander = Pokemon.new

那么,有没有办法以某种方式检索引用这两个对象(pikatchucharmander)?

So, is there a way I could somehow retrieve references those two objects (pikatchu and charmander)?

我实际上想通过 initialize 将它全部推入一个类数组中,但这可能会变大,我假设可能有一种原生的 Ruby 方法.

I actually thought of shoving it all into a class array via initialize, but that could potentially grow big, and I am assuming there might be a native Ruby approach to it.

推荐答案

解决方案是使用 ObjectSpace.each_object 方法如

The solution is to use ObjectSpace.each_object method like

ObjectSpace.each_object(Pokemon) {|x| p x}

产生

<Pokemon:0x0000010098aa70>
<Pokemon:0x00000100992158>
 => 2 

详细信息在 PickAxe 书籍第 25 章中讨论

Details are discussed in the PickAxe book Chapter 25

这篇关于如何在 Ruby 中查找类的每个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆