Modules included in a class
Someone over at comp.lang.ruby asked for a way to find out which modules had been included in a class. I guessed that the ancestors method (defined in the Module class) would be the key, and that Array’s select would be the… other key… Huh. Anyway, this does it (assuming a class C):
C.ancestors.select {|a| a.class == Module}
I even posted it as a solution. But what I should have looked closer, because there is exactly a method that does it, and it’s sort of obvious:
C.included_modules
Of course, I don’t know the Module methods by heart, and I had just assumed that he had already looked for something in the documentation.
Moral of the story: Never assume a person asking a question has even so much as tried anything out on irb or looked at the documentation.
Bonus moral: Matz names everything what you would name it (pretty much). You can guess at Ruby methods and get it right an awful lot.
Corey said,
July 9, 2007 @ 10:18 am
<p>I shame Matz for using is “instance_variable_set” and “instance_variable_get”. A hash called instance_variables or “set_instance_variable” seems like a better choice to me. But this is so insignificant I should stop my bellyaching.</p>