gpt4 book ai didi

Ruby 将参数传递给 block

转载 作者:太空宇宙 更新时间:2023-11-03 18:21:20 25 4
gpt4 key购买 nike

我有以下代码

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

更新:

错误,因为 block 返回字符串,但必须返回 block 或 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"

关于Ruby 将参数传递给 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17866100/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com