简体   繁体   English

访问块内定义的变量

[英]Accessing variable defined inside block

I have this snippet: 我有这个片段:

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

MyClass::callWithBlock do
    blockVar = 'Hello'
end

which gives me an error: 这给了我一个错误:

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

How to access this blockVar ? 如何访问此blockVar

If you add binding at the end of the block, that would become the result of call -ing the block, and you can eval whatever local variables assigned in that block within the context of the binding. 如果在块的末尾添加binding ,那将成为call块的结果,并且可以在绑定的上下文中eval该块中分配的任何局部变量。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM