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
254 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
trueif an only if the objectxis an eigenclass:The
===equality check asserts thatxis an instance of theClassclass, the!=inequality check uses the fact that theancestorsintrospection method "skips" eigenclasses. For objectsxthat are instances of theObjectclass (i.e.xis not a blank slate object), theClass === xcheck is equivalent tox.is_a? Classor, 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
truealso for classes that haveprepended modules. This can be solved by an additional check thatx.ancestors.firstis not such a prepended module e.g. byClass === x.ancestors.first. Another solution is to modify the whole expression as follows: