1

我想访问由我的 DSL 用户在一个块中声明的局部变量。

例如

class Scraper
  def scrape!(&block)

    a = block.binding
    instance_eval &block
    b = block.binding

    p "b] Notice that the variable named variable no longer exists here..."
    eval("p local_variables", a)

    p "or here ..."
    eval("p local_variables", b)

    p "Although, when we rerun the proc, all is still as it was..."
    pr = block.to_proc
    pr.call
    c = pr.binding
    p "Still nothing here though..."
    eval("p local_variables", c)
  end
end

s = Scraper.new
s.scrape! do
  variable = "some_value"
  p "A] Notice that the variable named variable clearly exists here..."
  p local_variables
end
4

1 回答 1

0

如果您认为您在 eval 中将某些内容传递给 local_variables 方法,以证明该变量不再存在,那么这不是您的代码中发生的情况。

局部变量确实是本地的,因此范围发生了变化,当范围发生变化时,范围变化的局部变量与您正在查看的另一个范围中的局部变量不同。

要获取这些局部变量,您必须处于该上下文中。Self 必须是该对象,然后您将可以访问这些局部变量。

因此,并不是那些区域中不再存在名为“变量”的变量,而是该变量从未存在于您所在的范围内。

局部变量并不意味着长期存在,真的。

现在如何找到他们?您可以通过将其作为方法的最后评估来获取内容。

于 2013-06-08T23:07:47.763 回答