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; end
returns the singleton class of Command
. 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 class C
or one of its subclasses. So by doing ObjectSpace.each_object(singleton_class_of_command)
you iterate over 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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With