从Ruby中的不同绑定访问局部变量
在Ruby中,您可以使用local_variables
和eval
编程方式轻松访问本地变量。 我真的希望使用单个方法调用对这些变量进行元编程访问,例如
# define a variable in this scope, such as x = 5 Foo.explore_locals # inside the Foo#explore_locals method, access x
其中Foo
是一些外部模块。 我们的想法是以一种很好的方式显示和导出局部变量。
explore_locals
方法应该包含哪些内容? 有没有办法让这成为可能? 如果绝对必要,我猜它可能会
Foo.explore_locals binding
但是对于我想到的应用程序来说,这并不那么优雅。
遗憾的是,没有内置的方式来获得调用者的绑定。 封锁技巧似乎是这个问题的通常答案。
然而,对于名为binding_of_caller
旧版1.8 Ruby版本存在另一个“技巧”。 看起来像quix将它移植到1.9。 您可能想要检查出来:
这是一个例子(但它需要额外的大括号{}
,如果可能的话我宁愿避免):
module Foo def self.explore_locals &block p block.binding.eval 'local_variables' end end local_1 = 3 Foo.explore_locals{} # shows [:local_1, :_]