Finding an Objects Class and Superclass

Finding an Object s Class and Superclass

Problem

Given a class, you want an object corresponding to its class, or to the parent of its class.

Solution

Use the Object#class method to get the class of an object as a Class object. Use Class#superclass to get the parent Class of a Class object:

'a string'.class # => String 'a string'.class.name # => "String" 'a string'.class.superclass # => Object String.superclass # => Object String.class # => Class String.class.superclass # => Module 'a string'.class.new # => ""

 

Discussion

Class objects in Ruby are first-class objects that can be assigned to variables, passed as arguments to methods, and modified dynamically. Many of the recipes in this chapter and Chapter 8 discuss things you can do with a Class object once you have it.

The superclass of the Object class is nil. This makes it easy to iterate up an inheritance hierarchy:

class Class def hierarchy (superclass ? superclass.hierarchy : []) << self end end Array.hierarchy # => [Object, Array] class MyArray < Array end MyArray.hierarchy # => [Object, Array, MyArray]

While Ruby does not support multiple inheritance, the language allows mixin Modules that simulate it (see Recipe 9.1). The Modules included by a given Class (or another Module) are accessible from the Module#ancestors method.

A class can have only one superclass, but it may have any number of ancestors. The list returned by Module#ancestors contains the entire inheritance hierarchy (including the class itself), any modules the class includes, and the ever-present Kernel module, whose methods are accessible from anywhere because Object itself mixes it in.

String.superclass # => Object String.ancestors # => [String, Enumerable, Comparable, Object, Kernel] Array.ancestors # => [Array, Enumerable, Object, Kernel] MyArray.ancestors # => [MyArray, Array, Enumerable, Object, Kernel] Object.ancestors # => [Object, Kernel] class MyClass end MyClass.ancestors # => [MyClass, Object, Kernel]

 

See Also

Категории