gpt4 book ai didi

ruby - 使用带参数的 instance_eval 调用 proc?

转载 作者:数据小太阳 更新时间:2023-10-29 06:25:07 25 4
gpt4 key购买 nike

我知道这行得通:

proc = Proc.new do
puts self.hi + ' world'
end

class Usa
def hi
"Hello!"
end
end
Usa.new.instance_eval &proc

但是我想将参数传递给 proc,所以我尝试了这个不起作用:

proc = Proc.new do |greeting| 
puts self.hi + greeting
end

class Usa
def hi
"Hello!"
end
end
Usa.new.instance_eval &proc, 'world' # does not work
Usa.new.instance_eval &proc('world') # does not work

谁能帮我让它工作?

最佳答案

使用instance_exec而不是 instance_eval当你需要传递参数时。

proc = Proc.new do |greeting| 
puts self.hi + greeting
end

class Usa
def hi
"Hello, "
end
end
Usa.new.instance_exec 'world!', &proc # => "Hello, world!"

注意:它是 Ruby 1.8.7 的新功能,因此如果需要,请升级或要求'backports'

关于ruby - 使用带参数的 instance_eval 调用 proc?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2759210/

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