Ruby enum_for confusion

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

 ObjectSpace.enum_for(:each_object, class << Command; self; end).to_a() 
+6
ruby
source share
1 answer

class << Command; self; end class << Command; self; end returns a singleton Command class. This is the class in which Command is the only (direct) instance.

In ruby, the singleton class of subclass C is a subclass of the C-singlet class. Thus, all Command subclasses have singleton classes that inherit from the command syntax class.

ObjectSpace.each_object(C) over all objects that are instances of class C or one of its subclasses. So, by executing ObjectSpace.each_object(singleton_class_of_command) , you ObjectSpace.each_object(singleton_class_of_command) over the command and all its subclasses.

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

+5
source share

All Articles