从Ruby中的不同绑定访问局部变量

时间:2011-07-05 23:12:10

标签: ruby metaprogramming

在Ruby中,您可以使用local_variableseval以编程方式轻松访问本地变量。我真的希望使用单个方法调用(例如

)对这些变量进行元编程访问
# 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

但是对于我想到的应用程序来说这不太优雅。

2 个答案:

答案 0 :(得分:1)

这是一个例子(但它需要额外的大括号{},如果可能的话我宁愿避免使用):

module Foo
  def self.explore_locals &block
    p block.binding.eval 'local_variables'
  end
end

local_1 = 3
Foo.explore_locals{}  # shows [:local_1, :_]

答案 1 :(得分:1)

遗憾的是,没有内置的方式来获得调用者的绑定。封锁技巧似乎是这个问题的通常答案。

然而,对于名为binding_of_caller的旧版1.8 Ruby版本,存在另一个“技巧”。看起来像quix将它移植到1.9。您可能想要检查出来:

https://github.com/quix/binding_of_caller