From: Markus Date: 2004-10-13T01:57:07+09:00 Subject: Re: closure's self On Tue, 2004-10-12 at 09:00, Mikael Brockman wrote: > "trans. (T. Onoma)" writes: > > > Curious thought --- what if I'd like to know the arity of the proc being > > executed? > > > > proc{|x| arity }.call(1) > > > > I see no way to do this, not even with the extended Binding class. I begin to > > wonder (for this and other reasons) if a closure's "self" is doable? (at > > least I think _closure_ is the right "scope" for this) > > > > proc{|x| this.arity }.call(1) > > > Closures per se don't have selfs -- they're not objects. Consider Ah, but they are Objects (as you make use of below). It's just that the binding used when their body is called that of their creation, not of themselves. > Here's an extremely ugly kludge: > > | class Proc > | alias :real_call :call > | > | def call *args > | old_proc = $current_proc > | $current_proc = self > | real_call *args > | $current_proc = old_proc > | end > | end > | > | (lambda do |x| > | puts $current_proc.arity > | (lambda do |x, y| > | puts $current_proc.arity > | end).call nil, nil > | puts $current_proc.arity > | end).call nil > > (It prints 1, 2, 1.) We could make id somewhat nicer if we use the "set_local" defined a few weeks back back on the list: WARNING: CODE TYPED DIRECTLY INTO EMAIL USING VAGUELY RECALLED EXPERIMENTAL FEATURE FROM ANOTHER E-MAIL THREAD class Proc alias :real_call :call def call *args binding.set_local("this_proc",self) real_call *args end end or even something like class Self_aware_proc << Proc def initialize(&block) super binding.set_local("this_proc",self) self end end or (IIRC): class Self_aware_proc << Proc def initialize(&block) super self["this_proc"] = self end end -- Markus