访问块内定义的变量

时间:2013-11-11 20:19:54

标签: ruby variables block

我有这个片段:

class MyClass
    def self.callWithBlock (&block)
        print block.blockVar
    end
end

MyClass::callWithBlock do
    blockVar = 'Hello'
end

给了我一个错误:

in `callWithBlock': undefined method `blockVar' for #<Proc:0x000000017ed168@./block-test.rb:9> (NoMethodError)
    from ./block-test.rb:9:in `<main>'

如何访问此blockVar

1 个答案:

答案 0 :(得分:2)

如果你在块的末尾添加binding,那将成为call块的结果,你可以eval在该块中分配的任何局部变量绑定的背景。

class MyClass
  def self.callWithBlock (&block)
    print block.call.eval('blockVar')
  end
end

MyClass::callWithBlock do
  blockVar = 'Hello'
  binding
end
# => Hello