从Ruby中的其他绑定访问局部变量 [英] Access local variables from a different binding in Ruby

查看:75
本文介绍了从Ruby中的其他绑定访问局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Ruby中,您可以使用local_variableseval轻松地以编程方式访问局部变量.我真的很想使用单个方法调用(例如

In Ruby, you can easily access local variables programmatically by using local_variables and eval. I would really like to have meta-programming access to these variables using a single method call such as

# define a variable in this scope, such as
x = 5
Foo.explore_locals  # inside the Foo#explore_locals method, access x

其中,Foo是某些外部模块.想法是以一种很好的方式显示和导出局部变量.

where Foo is some external module. The idea is to display and export local variables in a nice way.

explore_locals方法内应包含什么?有什么办法可以做到这一点?如果绝对必要,我想可能是

What should be inside the explore_locals method? Is there any way to make this possible? If absolutely necessary, I guess it could be

Foo.explore_locals binding

但是对于我所想到的应用程序而言,这并不那么优雅.

but this is much less elegant for the application I have in mind.

推荐答案

很遗憾,没有内置的方法来获取调用者的绑定.阻止技巧似乎是该问题的常见答案.

It's a shame there isn't a built-in way to get the caller's binding. The block trick seems to be the usual answer to this question.

但是,对于较旧的1.8 Ruby版本,存在另一个名为"binding_of_caller"的技巧".看起来像quix将其移植到1.9.您可能要检查一下:

However there is another 'trick' which existed for older 1.8 Ruby versions called binding_of_caller. Looks like quix ported it to 1.9. You might want to check that out:

https://github.com/quix/binding_of_caller

这篇关于从Ruby中的其他绑定访问局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆