tags:

views:

28

answers:

1

Hi,

I am trying to find all the subclasses of a certain type called Command in Ruby, and I came across the following code which did the trick perfectly, however I don't really understand how it works, mainly the class << [Subtype] part. I have tried reading up on this, but I feel there is still some Ruby magic which I am missing. Can someone please explain this to me :-)

ObjectSpace.enum_for(:each_object, class << Command; self; end).to_a()
+1  A: 

class << Command; self; end returns the singleton class of Command. This is the class that Command is the only instance of.

In ruby the singleton class of a class C is a subclass of C's singleton class. So all subclasses of Command have singleton classes that inherit from Command.

ObjectSpace.each_object(C) iterates over all objects that are instances of the class C or one of its subclasses. So by doing ObjectSpace.each_object(singleton_class_of_command) you iterate of Command and all its subclasses.

The enum_for bit returns an Enumerable that enumerates all the elements that each_object iterates over, so you can turn it into an array with to_a.

sepp2k
Brilliant explanation, thanks! So it is essentially the same as this: commands = [] ObjectSpace.each_object(class << Command; self; end) { |c| commands << c } it seems really simple now, I should have been able to work that out :)
amarsuperstar