From: David Alan Black Date: 2002-07-14T09:14:26+09:00 Subject: Re: instance_eval Hi -- On Sun, 14 Jul 2002, John wrote: > Hi all, > > I am trying to add a method dynamically. I can do the following just fine: > > def create > str = "def hello (*args) puts 'test' end" > self.instance_eval (str) > end > > This adds the hello method. But I want to pass a block to test so that it > executes the block instead of the "puts 'test'". > > I tried the following after searching some previous posts: > > def create (&block) > str = "def hello (*args) block.call end" > self.instance_eval (str) I believe that "self.instance_eval" is essentially the same as plain "eval", because instance_eval effectively sets the value of "self", temporarily, to its receiver -- so setting it to "self" doesn't change anything. (Stay tuned for others pointing out possible subtleties that I'm overlooking :-) Here's a little example of switching "self" on the fly, just for contrast: class Thing def demo puts "I am a #{type}" # => I am a Thing s = "string" s.instance_eval 'puts "I am a #{type}"' # => I am a String end end > end > > But to be honest I don't really know what I am doing there. ;-) I realize > that instance_eval can take a block, but what name would the method be? I'm almost, but not quite, following your description.... Which method do you mean? Could you explain a little more about the context? I think there might be useful things you could do along the lines of, maybe, a hash of Proc objects, or something like that, but I'm not sure what the best fit would be. David -- David Alan Black home: dblack@candle.superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav