From: "Daniel P. Zepeda" Date: 2003-02-09T16:32:01+09:00 Subject: Re: 'static' variables in a proc? On Sun, 9 Feb 2003 14:51:23 +0900 ptkwt@shell1.aracnet.com (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? > > I tried using an instance variable: > p = proc { unless defined? @a > @a = 1 > end > puts @a > @a+=1 > } > # > irb(main):024:0> p.call > true > NameError: undefined method `+' for true > from (irb):22 > from (irb):18:in `call' > from (irb):24 > > I'm not sure why @a became true... > > Then I tried: > > p = proc{ unless defined? a > a = 1 > end > puts a > a += 1 > } > > > ....and of course all I ever get out of it is 1, but at least a doesn't > become 'true'. There's a couple of ways to do it, you could just define 'a' outside the proc, this might suffice depending on what you're doing: a = 0 p = proc { a += 1; puts a} 1.upto( 3 ) { p.call } a more general method would be to put 'a' in a singleton class: require 'singleton' class MyA include Singleton attr_accessor :a def initialize @a = 0 end end q = proc { a = MyA.instance; a.a += 1; puts a.a} 1.upto( 3 ) { q.call } > > > Phil -- Daniel P. Zepeda