【问题标题】:Ruby pass arguments to blockRuby 将参数传递给阻塞
【发布时间】:2013-07-25 18:36:02
【问题描述】:

我有以下代码

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。

【问题讨论】:

标签: ruby metaprogramming


【解决方案1】:
...
  #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"

【讨论】:

  • 简单而强大。谢谢
猜你喜欢
  • 2012-09-12
  • 2012-03-15
  • 2021-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多