From: "Ara.T.Howard" Date: 2005-07-20T01:40:23+09:00 Subject: Re: Instance Eval of a Proc On Wed, 20 Jul 2005, Jacob Fugal wrote: > On 7/19/05, Ara.T.Howard wrote: >> On Wed, 20 Jul 2005, Gavin Kistner wrote: >> >>> [Slim:~/Desktop] gavinkis% cat instance_eval_proc.rb >>> class Foo >>> def self.show_name( *args ) >>> puts "Foo.show_name says that @name is '#@name' for #{self.inspect}" >>> end >>> def initialize( name ) >>> @name = name >>> end >>> end >>> >>> f = Foo.new( "Jim" ) >>> >>> my_lambda = lambda{ >>> puts "my_lambda says that @name is '#@name' for #{self.inspect}" >>> } >>> p my_lambda >>> f.instance_eval( &my_lambda ) >>> >>> my_proc = Proc.new{ >>> puts "my_proc says that @name is '#@name' for #{self.inspect}" >>> } >>> p my_proc >>> f.instance_eval( &my_proc ) >>> >>> meth_lambda = Foo.method( :show_name ).to_proc >>> p meth_lambda >>> f.instance_eval( &meth_lambda ) >> >> just because you are call meth_lambda in instance_eval doesn't mean >> @name will be defined. > > I think Gavin's point is that it *does* work for my_lambda and > my_proc. meth_lambda is the only exception. Neither my_lambda nor > my_proc knew about @name either when they were defined. instance_eval > bound self to the caller for the evaluation of the proc. However, the > same binding didn't take place for meth_lambda, and it used Foo as > self instead of f. well: harp:~ > ri Object.method ---------------------------------------------------------- Object#method obj.method(sym) => method ------------------------------------------------------------------------ Looks up the named method as a receiver in _obj_, returning a +Method+ object (or raising +NameError+). The +Method+ object acts as a closure in _obj_'s object instance, so instance variables and the value of +self+ remain available. ... ... ... so i don't really see the exception - the behaviour of Foo.method(:show_name) does exactly as advertised - binding the method to the class Foo along with that notion of self and instance vars. so the binding of self for the duration of instance_eval is definitely working - what gavin is attempting to do is akin to hoping f.instance_eval do p ::File::LOCK_EX end would somehow print some other class/objects constant named 'LOCK_EX' in that the caller/scope-resolution for show_name is already set after the call to Foo::method. in the cases like f.instance_eval &my_proc it has not already been set and is then set for the call. eg. Foo::method binds exactly as f.instance_eval does - only a layer deeper. anyhow it seems consistent - but perhaps not intuitive. kind regards. -a -- =============================================================================== | email :: ara [dot] t [dot] howard [at] noaa [dot] gov | phone :: 303.497.6469 | My religion is very simple. My religion is kindness. | --Tenzin Gyatso ===============================================================================