Ruby将参数传递到块
我有以下代码Ruby将参数传递到块,ruby,metaprogramming,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 chang
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#为什么不使用实例?
“测试”
4.rb:14:in'call_block':错误的参数类型字符串(预期过程)(TypeError)
来自测试。rb:20:in`'
为什么会有这样的结果?如何将作用域从SomeClass更改为SomeClass实例
UPD:
错误,因为块返回字符串,但必须是返回块、lambda或proc。。。。
...
#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"
#使用参数调用块并更改上下文
def调用块(arg)
block=@@block
实例执行(参数和块)
结束
结束
s=SomeClass.new
s、 调用块(“测试”)
#
“测试”
简单而强大的功能可能重复。谢谢