What is the best way to tell if a class some_class
is an eigenclass of some object?
Knowing if a class is an eigenclass
258 Views Asked by sawa At
3
What is the best way to tell if a class some_class
is an eigenclass of some object?
(Prior to Ruby 2.0) The following expression evaluates to
true
if an only if the objectx
is an eigenclass:The
===
equality check asserts thatx
is an instance of theClass
class, the!=
inequality check uses the fact that theancestors
introspection method "skips" eigenclasses. For objectsx
that are instances of theObject
class (i.e.x
is not a blank slate object), theClass === x
check is equivalent tox.is_a? Class
or, in this particular case, tox.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 haveprepend
ed modules. This can be solved by an additional check thatx.ancestors.first
is not such a prepended module e.g. byClass === x.ancestors.first
. Another solution is to modify the whole expression as follows: