0

我有这个片段:

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

4

1 回答 1

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
于 2013-11-11T20:30:42.993 回答