From: Hugh Sasse Date: 2005-11-17T00:11:45+09:00 Subject: Re: static variable; behaviour in ruby? On Wed, 16 Nov 2005, Ara.T.Howard wrote: > On Wed, 16 Nov 2005, Hugh Sasse wrote: > > > Any idea how to create or simulate a static variable in ruby? [...] > > 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 > ["x", "y", "z"] [etc] Maybe something like def my_method x, y, z, &block state = rand # do something with x, y, z alias :old_my_method, :my_method define_method(:my_method)(x,y,z, &block) lambda{ block[x, y, z] if state < 0.42 }.call end end might do the trick, then? The state would get carried around with the closure in subesequent calls to the same method? Except having sevaral calls in the same block would be treated the same as severl calls to the same method, rather than the way sed treats /this/,/that/{ statements}, each heing independent, runnin for each line of the input. > > > > Maybe there's another way to do this? > > write it in assembler ;-) :-) > Hugh