Ruby传递参数阻止

时间:2013-07-25 18:36:02

标签: ruby metaprogramming

我有以下代码

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实例?

UPD:

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

1 个答案:

答案 0 :(得分: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"