Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get all the eigenclasses in Ruby?

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.

like image 382
Andrew Grimm Avatar asked Oct 19 '11 03:10

Andrew Grimm


2 Answers

If you mean objects that have singleton methods, this should work.

eigens = []
ObjectSpace.each_object do |object|
  eigens << object unless object.singleton_methods.empty?
end

If not, could you clarify? I used this discussion as a reference:

http://www.ruby-forum.com/topic/77046

like image 112
sheldonh Avatar answered Oct 23 '22 12:10

sheldonh


I doubt this is what you want, but it should return all eigenclasses:

eigens = ObjectSpace.each_object.collect { |obj| class << obj; self; end }

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.

like image 44
Ryan Sandridge Avatar answered Oct 23 '22 11:10

Ryan Sandridge