Easy introspection in Ruby

Just some notes on reflection and introspection in Ruby


someString = 'http://google.com'

# Print the object's class, methods, superclass and
# ancestors (mixins and superclasses),
p someString.class
p someString.methods
p someString.class.superclass
p someString.class.ancestors

# Print the methods of the String class.
p String.private_instance_methods(false)
p String.public_instance_methods(false)

# Pass true to recurse into parent classes.
p String.public_instance_methods(true)

# Calling instance methods with send().
"Random text".send(:length) # 11
-23.send(:succ) # 22

# Using Method objects and call().
length_method = "Random text".method(:length)
length_method.call # 11

# Another way, using eval().
length_method = %q{"Random text".length}
eval length_method

Check out Distributed Ruby (DRb): it’s a very neat, non-fancy way of exposing object methods as remote services.

Comments & TrackBacks ()

There are no comments yet. Somebody say something!

You can subscribe to the RSS feed for comments on this post.

Sorry, this entry is no longer accepting comments. If you have something you really want to say, you can write me.