Further Dementia
I got an e-mail response from ged/m.g. today concerning the demented wishes. He pointed out that Ruby 1.8 does have Class#define_method. So I peeked into rb_mod_define_method() to see how it works exactly.
As you’d suspect, Procs and blocks are basically converted to Methods. Given a name and bound to a class. Which has me wondering why all Procs shouldn’t just become Methods. The default would be for each block to be a method belonging to a singleton of a scope instance. That way you could access the methods of that scope and store metadata during a block’s execution.
Here’s some proof-of-concept code. There are certainly problems with this idea. It feels dangerous, but I figure that this is one entry on one small site and out of view. Please don’t squeal on me.
class ProcScope
attr :count
def initialize( &p )
class << self
define_method( :proc_call, &p )
end
def call( *x )
@count ||= 0
@count += 1
proc_call( *x )
end
end
end
class Array
def each_p( &p )
s = ProcScope.new( &p )
each { |x| s.call( x ) }
end
end
[ 'a', 'b', 'c' ].each do |x|
puts count
end
I’m still not sure what I think about the whole idea. It’s neat. Solves some problems. Creates some problems. I just know there’s a good angle on this. Looking for it…
