I just figured out what Ruby was doing, because I forgot just how “meta” my programming was. Consider this code frag:
def const_missing(symbol)
alias_const_missing(symbol) unless symbol == :ArrayList
obj = create_clr_class_object
# remember that the code below is in a string
obj.class_eval %{
def initialize(*params)
create_safe_ruby_instance_method(
self.class, 'initialize') do
include 'System.Collections'
declare "#{symbol}", :obj
...
Look at the last line of code and the declare statement. Notice how I’m referencing the symbol variable that is the input parameter to the const_missing method declaration on the first line? I have to escape that reference as a string to access that variable. Why? Because that code is embedded in a string (that’s what the funny %{ means: it’s a begin string quotation symbol).
Now this has interesting implications for other string manipulation functions that are inside of the string that is passed to obj.class_eval. For example consider this snippet of code.
sigs = get_constructor_signatures("#{symbol}")
switch_labels = (1..sigs.length).collect { |i| ("l" + i.to_s).to_sym }
I really wanted to write the string expression as:
"l#{i}".to_sym
But this cannot work since it would try and find an i variable defined in the enclosing method. So I wound up writing it in the somewhat more verbose way that I did to make it work. I wound up scratching my head about this behavior for quite a while before I realized that, doh! the code was executing inside of a string.
That’s how powerful Ruby’s metaprogramming facilities are: oftentimes you forget that you’re really programming at a meta level of abstraction instead of at the “concrete” level.