I've been having a problem with a pesky little function in a class in a library that I did not create (and thus, cannot edit). Here's a simple class with the annoying behavior isolated:
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 run into a problem when I try to iterate and generate an array of these objects. I expected a different value to be substituted for i
into the Proc with each object, but what happens instead is that the variable i
is shared between them.
$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
Output
15 15
What can I do inside the loop to preserve separate values of i
for each object?