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

  • Most of Chapter 8
  • Recipe 9.1, "Simulating Multiple Inheritance with Mixins"


Strings

Numbers

Date and Time

Arrays

Hashes

Files and Directories

Code Blocks and Iteration

Objects and Classes8

Modules and Namespaces

Reflection and Metaprogramming

XML and HTML

Graphics and Other File Formats

Databases and Persistence

Internet Services

Web Development Ruby on Rails

Web Services and Distributed Programming

Testing, Debugging, Optimizing, and Documenting

Packaging and Distributing Software

Automating Tasks with Rake

Multitasking and Multithreading

User Interface

Extending Ruby with Other Languages

System Administration



Ruby Cookbook
Ruby Cookbook (Cookbooks (OReilly))
ISBN: 0596523696
EAN: 2147483647
Year: N/A
Pages: 399

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net