Types, Classes, and Modules
The most commonly used reflective methods are those for determining the type of an object—what class it is an instance of and what methods it responds to. We introduced most of these important methods early in this book in Object Class and Object Type. To review:
o.classReturns the class of an object
o.c.superclassReturns the superclass of a class
c.o.instance_of? cDetermines whether the object
o.class == c.o.is_a? cDetermines whether
ois an instance ofc, or of any of its subclasses. Ifcis a module, this method tests whethero.class(or any of its ancestors) includes the module.o.kind_of? ckind_of?is a synonym foris_a?.c === oFor any class or module
c, determines ifo.is_a?(c).o.respond_to? nameDetermines whether the object
ohas a public or protected method with the specified name. Passtrueas the second argument to check private methods as well.
Ancestry and Modules
In addition to these methods that you’ve already seen, there are a few related reflective methods for determining the ancestors of a class or module and for determining which modules are included by a class or module. These methods are easy to understand when demonstrated:
module A; end # Empty module module B; include A; end; # Module B includes A class C; include B; end; # Class C includes module B C < B # => true: C includes B B < A # => true: B includes A C < A # => true Fixnum < Integer # => true: all fixnums are integers Integer < Comparable # => true: integers are comparable Integer ...