是否有可能获得 Ruby 中的所有特征类?
在 Ruby 中获取所有模块的列表很容易:
ObjectSpace.each_object(Module).to_a
但是,是否可以获取所有特征类(也称为单例类或元类)的列表?或者特征类是不可见的?
我尝试
str = "foo"
my_metaclass = class << str; self; end
my_metaclass.class == Class # my_metaclass' class is Class
ObjectSpace.each_object(Class).include?(my_metaclass) # false
ObjectSpace.each_object.include?(my_metaclass) # still false
# Just to show each_object works
ObjectSpace.each_object(Class).include?(String) # true
获取特征类,因为我想列出脚本中定义的所有方法。我可以查找模块和类定义的所有实例方法,然后查找模块和类的单例方法(或者所有对象的单例方法,如果我想消耗 CPU 的话),但这似乎有点黑客。
Getting a list of all modules is easy in Ruby:
ObjectSpace.each_object(Module).to_a
However, is it possible to get a list of all eigenclasses (also known as singleton classes or metaclasses)? Or are eigenclasses invisible?
I tried
str = "foo"
my_metaclass = class << str; self; end
my_metaclass.class == Class # my_metaclass' class is Class
ObjectSpace.each_object(Class).include?(my_metaclass) # false
ObjectSpace.each_object.include?(my_metaclass) # still false
# Just to show each_object works
ObjectSpace.each_object(Class).include?(String) # true
I'm trying to get eigenclasses because I'm wanting to list all the methods that are defined within a script. I could look for all the instance methods defined by modules and classes, and then look for singleton methods of modules and classes (or of all objects, if I want to chew up CPU), but that seems a little hackish.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您指的是具有单例方法的对象,那么这应该可行。
如果没有,你能澄清一下吗?我将此讨论用作参考:
http://www.ruby-forum.com/topic/77046
If you mean objects that have singleton methods, this should work.
If not, could you clarify? I used this discussion as a reference:
http://www.ruby-forum.com/topic/77046
我怀疑这就是你想要的,但它应该返回所有特征类:
这确实会将所有特征类的数组分配给变量特征。问题是,Ruby 实现可能实际上不会创建特征类,除非需要它,并且此代码(我相信)实际上会创建特征类,即使是不需要的对象。
如果找到更好的方法很重要,我会将问题发送给任何 Ruby 实现的实现者之一(@yukihiro_matz、@evanphx、@headius 等等)。如果有人知道的话,他们就会的。
I doubt this is what you want, but it should return all eigenclasses:
That will indeed assign an array of all the eigenclasses to the variable eigens. The thing is, Ruby implementations likely don't actually create an eigenclass unless there is a need for it, and this code (I believe) will actually create the eigen classes even for the objects where one wasn't needed.
If finding a better way is important, I'd tweet the question to one of the implementors of any of the Ruby implementations (@yukihiro_matz, @evanphx, @headius to name a few that come to mind). If anybody would know, they would.
从 MRI 1.9 开始,似乎不支持特征类枚举。作为(半)后果,没有 100% 可靠的方法来迭代所有方法。整体方法枚举器的最佳近似如下
但是,此代码不会枚举
As of MRI 1.9, eigenclass enumeration does NOT seem to be supported. As a (semi-)consequence, there is no 100%-reliable way to iterate over all methods. The best approximation for an overall method enumerator is as follows
However, this code will NOT enumerate