From: "Ara.T.Howard" Date: 2005-11-16T23:07:28+09:00 Subject: Re: static variable; behaviour in ruby? On Wed, 16 Nov 2005, Hugh Sasse wrote: > Any idea how to create or simulate a static variable in ruby? > > I want to create a variable to hold state between calls of a method, > but have the state disappear when the method goes out of scope. > I could create it in some external object but then I'd need to query > the scoping rules, and know where i was. > > I'm trying to do an instance_eval on a string containing a method such as > do_this x,y,z {block} > and I want to evaluate the block, or not, as a function of some > state against which x,y,z are compared. The code will be called several > times, but I only want the state intialized the first time the scope > is entered. > > And, just to make matters worse, there could be several independent > calls to this method within the scope, each with its own separate > state. harp:~ > cat a.rb def do_this_factory x, y, z, &block state = rand # do something with x, y, z lambda{ block[x, y, z] if state < 0.42 } end a = do_this_factory 'x','y','z' do |x,y,z| p [x,y,z] end a.call harp:~ > ruby a.rb harp:~ > ruby a.rb harp:~ > ruby a.rb ["x", "y", "z"] harp:~ > ruby a.rb harp:~ > ruby a.rb ["x", "y", "z"] harp:~ > ruby a.rb ["x", "y", "z"] > Maybe there's another way to do this? write it in assembler ;-) -a -- =============================================================================== | ara [dot] t [dot] howard [at] gmail [dot] com | all happiness comes from the desire for others to be happy. all misery | comes from the desire for oneself to be happy. | -- bodhicaryavatara ===============================================================================