rubyeigenclass

Knowing if a class is an eigenclass


What is the best way to tell if a class some_class is an eigenclass of some object?


Solution

  • (Prior to Ruby 2.0) The following expression evaluates to true if an only if the object x is an eigenclass:

    Class === x && x.ancestors.first != x
    

    The === equality check asserts that x is an instance of the Class class, the != inequality check uses the fact that the ancestors introspection method "skips" eigenclasses. For objects x that are instances of the Object class (i.e. x is not a blank slate object), the Class === x check is equivalent to x.is_a? Class or, in this particular case, to x.instance_of? Class.

    Starting with Ruby 2.0, the above expression is not sufficient to detect eigenclasses since it evaluates to true also for classes that have prepended modules. This can be solved by an additional check that x.ancestors.first is not such a prepended module e.g. by Class === x.ancestors.first. Another solution is to modify the whole expression as follows:

    Class === x && !x.ancestors.include?(x)