Easy introspection in Ruby

In: Ruby

9 Aug 2006

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 are closed.