O'Reilly logo

Learning Ruby by Michael Fitzgerald

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Reflection

Ruby can easily tell you about itself—its programs and objects—through methods that, taken as a whole, constitute a feature called reflection. You've seen a few of these methods in action earlier in this book. I'll go over some of the most frequently called methods and point out some others you may find useful.

Using a here document (see Chapter 4), I'll define a string, a bit of a Walt Whitman poem, and then do some reflecting on it.

asiponder = <<whitman
As I ponder'd in silence,
Returning upon my poems, considering, lingering long,
A Phantom arose before me, with distrustful aspect,
Terrible in beauty, age, and power,
The genius of poets of old lands
whitman # => "As I ponder'd in silence, \nReturning upon
my poems, considering, lingering long, \nA Phantom arose before me, with distrustful
aspect, \nTerrible in beauty, age, and power, \nThe genius of poets of old lands\n"

asiponder is an instance of the String class. The Object class has a class method that returns the name of an instance's class:

asiponder.class # => String

The class method supercedes Object's deprecated method type, or gets the name of the class as a string with the name method:

asiponder.class.name # => "String"

To determine the name of the superclass—the parent class that is one step higher in the class hierarchy—use the superclass method from Class.

asiponder.class.superclass # => Object
String.superclass # => Object

Discover the names of any of the included modules of an instance or its class using the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required