gpt4 book ai didi

ruby - 使用变量的当前值创建 Proc

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

我在库中的一个类中遇到了一个讨厌的小函数的问题,该函数不是我创建的(因此无法编辑)。这是一个简单的类,其中包含烦人的行为:

class Foo              # This is a class I cannot
def setmyproc(&code) # safely edit.
@prc = Proc.new # Due to it being in a
end # frustratingly complex
def callmyproc() # hierarchy, I don't
@prc.call # even know how to reopen
end # it. Consider this class
end # set in stone.

当我尝试迭代并生成这些对象的数组时遇到了问题。我希望用一个不同的值代替 i 到每个对象的 Proc 中,但实际上发生的是变量 i 在它们之间共享。

$bar = []
for i in (0..15)
$bar[i] = Foo.new
$bar[i].setmyproc { puts i }
end

$bar[3].callmyproc # expected to print 3
$bar[6].callmyproc # expected to print 6

输出

  15  15

我可以在循环内做些什么来为每个对象保留单独的 i 值?

最佳答案

使用这个:

$bar = []
(0..15).each do |i|
$bar[i] = Foo.new
$bar[i].setmyproc { puts i }
end

$bar[3].callmyproc # prints 3
$bar[6].callmyproc # prints 6

如果您确实需要在循环内部进行更改,请使用它(仅限 ruby​​ 1.9):

$bar = []
for i in (0..15)
->(x) do
$bar[x] = Foo.new
$bar[x].setmyproc { puts x }
end.(i)
end

$bar[3].callmyproc # prints 3
$bar[6].callmyproc # prints 6

关于ruby - 使用变量的当前值创建 Proc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3146244/

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