【问题标题】:Ruby: retrieve local_variables from a block or append code within a blockRuby:从块中检索 local_variables 或在块中附加代码
【发布时间】:2013-06-08 21:38:37
【问题描述】:

我想访问我的 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

【问题讨论】:

    标签: ruby scope metaprogramming block dsl


    【解决方案1】:

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

    局部变量确实是局部的,所以作用域发生了变化,当作用域发生变化时,你作用域的局部变量与你在另一个作用域中看到的局部变量不同。

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

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

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

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

    【讨论】:

    • 这就是我试图用我的示例来说明的内容,如何添加一行以从 proc 中返回绑定?
    猜你喜欢
    • 2015-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-10
    • 2013-11-12
    • 1970-01-01
    • 2016-04-05
    • 2015-08-04
    相关资源
    最近更新 更多