Wednesday, December 29, 2010

Ruby: Introspection

Supposedly, Ruby has introspection, but some things are missing. For example:

# How to get the name of the current method?
# Add this snippet of code to your logic somewhere
module Kernel
  # Defined in ruby 1.9
  unless defined?(__method__)
    def __method__
      caller[0] =~ /`([^']*)'/ and $1
In Python, this is not much better:

import tracebackdef asdf():
    print function_name

Update: __method__ is part of Ruby as of 1.8.7.

Here is something else rather awkward in Ruby:

# Print all modules (excluding classes)
puts {|x| eval(x.to_s).instance_of? Module}
In Python, we could simply do this:
import sys; print sys.modules.keys()
Ruby's introspection (also) reveals a lot about the structure of classes.

No comments:

Post a Comment