1

我有以下代码

class SomeClass
  #define method, which take block and save it into class variable   
  def self.test(&block)
    @@block = block
  end
  #pass block to method  
  test do |z|
    p self 
    p z
  end
  #call block with argument and change context
  def call_block(arg)
    block = @@block
    instance_eval &block.call(arg)
  end
end

s = SomeClass.new
s.call_block("test")

我得到了输出

SomeClass  # Why not instance? 
"test"
4.rb:14:in `call_block': wrong argument type String (expected Proc) (TypeError)
from test.rb:20:in `<main>'

为什么是结果?如何将范围从 SomeClass 更改为 SomeClass 实例?

升级版:

错误,因为块返回字符串,但必须是返回块或 lambda 或 proc。

4

1 回答 1

3
...
  #call block with argument and change context
  def call_block(arg)
    block = @@block
    instance_exec(arg, &block)
  end
end

s = SomeClass.new
s.call_block("test")

#<SomeClass:0x10308ad28>
"test"
于 2013-07-25T19:33:25.873 回答