开发者

ruby lambda context

开发者 https://www.devze.com 2023-01-04 20:00 出处:网络
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 wou

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 er开发者_开发百科ror "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.


the code you are looking for is

temp.instance_eval(&callable)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号