This post originated from an RSS feed registered with Web Buzz
by Cheah Chu Yeow.
Original Post: Easy Introspection in Ruby
Feed Title: redemption in a blog
Feed URL: http://blog.codefront.net/xml/rss20/feed.xml
Feed Description: ramblings of a misfit - web development, Mozilla, Firefox, Thunderbird, CSS, programming
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.