红宝石lambda上下文 [英] ruby lambda context
问题描述
让我们在最顶层定义以下红宝石定义
Lets say I have the following ruby definition at the topmost level
callable = lambda {"#{hi}"}
,并假设稍后我创建一个名为temp
的对象,该对象具有一个名为hi
的方法.现在我想做的是在temp
的上下文中调用callable
.我已经尝试过了
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
但是这给了我错误"NameError: undefined local variable or method 'hi' for main:Object
".我想知道是否有任何方法可以将callable
的上下文重新绑定到temp
,这样我就不会收到错误消息?我知道我可以在main:Object上定义method_missing
并将所有方法调用重新路由到temp
,但这似乎实在太大了,无法完成我想要的事情.
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.
推荐答案
您正在寻找的代码是
temp.instance_eval(&callable)
这篇关于红宝石lambda上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!