Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby enum_for confusion

Tags:

ruby

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()
like image 847
amarsuperstar Avatar asked Jun 27 '10 11:06

amarsuperstar


1 Answers

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.

like image 55
sepp2k Avatar answered Oct 14 '22 10:10

sepp2k