From: "Ara.T.Howard" Date: 2005-07-20T00:52:04+09:00 Subject: Re: Instance Eval of a Proc On Wed, 20 Jul 2005, Gavin Kistner wrote: > Why can I not use a Proc created from a method in #instance_eval? (Or rather, > am I making a mistake, or is there a way to do this?) > > Related: are first-class functions planned for 2.0? The whole Proc/ > block/method situation needs unifying and simplifying, IMHO. > > > [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. imagine that you'd written this instead f.instance_eval{ Foo::show_name } of course this is exactly what's happening - you've used the class Foo to look up a class method that prints an uninitialized class variable. the fact that this whole business gets wrapped in another proc (Foo.method(:show_name).to_proc) still doesn't initialize it nor bind the instance's @name to the class @name somehow. probably doing something like f.instance_eval do f.class.instance_eval{ @name = 'Jim' } meth_lambda.call end might though. another approach would be (i think) to 'install' the class method as an instance one using define_method or something. cheers. -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 ===============================================================================