views:

56

answers:

1

Lets say I have the following ruby definition at the topmost level

callable = lambda {"#{hi}"}

and suppose that later on I create an object called temp that has a method called hi. Now what I would like to do is call callable within the context of temp. I have tried doing

temp.instance_eval do callable.call end

but this gives me the error "NameError: undefined local variable or method 'hi' for main:Object". I would like to know if there is any way to rebind the context of callable to temp so that I don't get an error message? I know that I could define method_missing on main:Object and reroute all method calls to temp but this seems like way too big of a hack to accomplish what I want.

+3  A: 

the code you are looking for is

temp.instance_eval(&callable)
Glenjamin
davidk01
@davidk01: b/c a Proc normally uses the context in which it is defined. instance_eval forces the given proc to use the context of the calling object, but doesn't do so recursively (so procs called w/in that proc are not context-shifted).
rampion
davidk01
rampion
davidk01
@rampion: Ha, I just got it. Thanks for the explanation it took me a while to figure out what you meant by>but doesn't do so recursively
davidk01
Glenjamin