If it's the same Proc object then it will have no idea that it is being
called from different places, so you would have to pass in an object as a
parameter where it can store its state.
It's simpler just to generate a separate Proc object for each time you use
it, so each carries its own state:
def factory
a = 1
proc {
puts a
a = a.succ
}
end
p1 = factory
p2 = factory
p1.call # >> 1
p1.call # >> 2
p2.call # >> 1
p2.call # >> 2
Your strangeness with '@a' was probably due to you doing previous stuff in
irb, because it works for me if I paste it into a fresh irb session:
$ irb
irb(main):001:0> p = proc { unless defined? @a
irb(main):002:2> @a = 1
irb(main):003:2> end
irb(main):004:1> puts @a
irb(main):005:1> @a+=1
irb(main):006:1> }
=> #<Proc:0x81627a0>
irb(main):007:0> p.call
1
=> 2
But the trouble with that code is, which object actually contains the
instance variable?? If I add
puts "I am #{self.inspect}"
at the end of that proc, I get
1
I am #<Object:0x8119cd8 @a=2>
So it's not the Proc object itself, and it's not the main execution
environment (where puts self.inspect shows "main"). Too confusing... that's
why I'd recommend the Proc 'factory' instead.
The code wouldn't be affected by the new scope rules, except that you
wouldn't have to define 'a=1' before the proc. Under the current rules, if
'a=' first appears in the proc body then it is a local variable to that
proc, and gets a fresh copy each time the proc is called.
Regards,
Brian.
···
On Sun, Feb 09, 2003 at 05:31:32PM +0900, Phil Tomson wrote:
>> Is there a way to get a variable in a proc that maintains it's value
>> between different calls of the proc?
>
>a = 1
>p = proc {
> puts a
> a+=1
>}
>
Right, I know that would work, but it's not exactly what I'm looking for
in this case as I might want to use the proc in several places and I would
like to have 'a' be different in each.