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()
class << Command; self; endreturns the singleton class ofCommand. This is the class that Command is the only (direct) instance of.In ruby the singleton class of a subclass of C is a subclass of C’s singleton class. So all subclasses of Command have singleton classes that inherit from Command’s singleton class.
ObjectSpace.each_object(C)iterates over all objects that are instances of the classCor one of its subclasses. So by doingObjectSpace.each_object(singleton_class_of_command)you iterate over Command and all its subclasses.The
enum_forbit returns an Enumerable that enumerates all the elements thateach_objectiterates over, so you can turn it into an array withto_a.