我有这个片段:
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
?
答案 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